This is the EAFP way, which avoids races and unneeded syscalls:
import errno
import os
import shutil
src = "./blah.txt"
dest = "./a/b/c/blah.txt"
# with open(src, 'w'): pass # create the src file
try:
shutil.copy(src, dest)
except IOError as e:
# ENOENT(2): file does not exist, raised also on missing dest parent dir
if e.errno != errno.ENOENT:
raise
# try creating parent directories
os.makedirs(os.path.dirname(dest))
shutil.copy(src, dest)
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.
A lot of the other answers are for older versions of Python, although they may still work, you can handle errors a lot better with newer Pythons.
If you are using Python 3.3 or newer, we can catch FileNotFoundError instead of IOError. We also want to differentiate between the destination path not existing and the source path not existing. We want to swallow the former exception, but not the latter.
Finally, beware that os.makedirs() recursively creates missing directories one at a time--meaning that it is not an atomic operation. You may witness unexpected behavior if you have multiple threads or processes that might try to create the same directory tree at the same time.
def copy_path(*, src, dst, dir_mode=0o777, follow_symlinks: bool = True):
"""
Copy a source filesystem path to a destination path, creating parent
directories if they don't exist.
Args:
src: The source filesystem path to copy. This must exist on the
filesystem.
dst: The destination to copy to. If the parent directories for this
path do not exist, we will create them.
dir_mode: The Unix permissions to set for any newly created
directories.
follow_symlinks: Whether to follow symlinks during the copy.
Returns:
Returns the destination path.
"""
try:
return shutil.copy2(src=src, dst=dst, follow_symlinks=follow_symlinks)
except FileNotFoundError as exc:
if exc.filename == dst and exc.filename2 is None:
parent = os.path.dirname(dst)
os.makedirs(name=parent, mode=dir_mode, exist_ok=True)
return shutil.copy2(
src=src,
dst=dst,
follow_symlinks=follow_symlinks,
)
raise