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


First thing I have to mention here, I'm new to python.

Now I have a file located in:


I want to copy to my home directory with a new folder created:


My expected result is:


Is there any existing library to do that? If no, how can I achieve that?

1/3/2019 6:28:03 AM

Accepted Answer

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

import os
import shutil

srcfile = 'a/long/long/path/to/'
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)
2/25/2014 1:11:23 PM

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow