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?
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.
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.
Use os.makedirs to create the directory tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With