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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…