create destination path for shutil.copy files

Solution 1:

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.

Solution 2:

Use os.makedirs to create the directory tree.

Solution 3:

I use something similar to this to check if the directory exists before doing things with it.

if not os.path.exists('a/b/c/'):
    os.mkdir('a/b/c')

Solution 4:

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)

Solution 5:

For 3.4/3.5+ you can use pathlib:

Path.mkdir(mode=0o777, parents=False, exist_ok=False)


So if there might be multiple directories to create and if they might already exist:

pathlib.Path(dst).mkdir(parents=True, exist_ok=True)