Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create destination path for shutil.copy files

Tags:

python

If a path such as b/c/ does not exist in ./a/b/c , shutil.copy("./blah.txt", "./a/b/c/blah.txt") will complain that the destination does not exist. What is the best way to create both the destination path and copy the file to this path?

like image 403
james Avatar asked May 08 '10 11:05

james


People also ask

Does Shutil copy create directories?

Use the copytree() method of a shutil module to copy the directory recursively. This method recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory.


2 Answers

To summarize info from the given answers and comments:

For python 3.2+:

os.makedirs before copy with exist_ok=True:

os.makedirs(os.path.dirname(dest_fpath), exist_ok=True) shutil.copy(src_fpath, dest_fpath) 

For python < 3.2:

os.makedirs after catching the IOError and try copying again:

try:     shutil.copy(src_fpath, dest_fpath) except IOError as io_err:     os.makedirs(os.path.dirname(dest_fpath))     shutil.copy(src_fpath, dest_fpath) 

Although you could be more explicit about checking errno and/or checking if path exists before makedirs, IMHO these snippets strike a nice balance between simplicity and functionality.

like image 81
7yl4r Avatar answered Oct 13 '22 04:10

7yl4r


Use os.makedirs to create the directory tree.

like image 36
Philipp Avatar answered Oct 13 '22 06:10

Philipp