How to copy a file along with directory structure/path using python? [duplicate]

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile="a/long/long/path/to/file.py"
dstroot="/home/myhome/new_folder"


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

Leave a Comment

tech