How do I copy an entire directory of files into an existing directory using Python?
Here's a solution that's part of the standard library:
from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")
See this similar question.
Copy directory contents into a directory with python
- Reference - https://docs.python.org/3/distutils/apiref.html#distutils.dir_util.copy_tree
This limitation of the standard shutil.copytree
seems arbitrary and annoying. Workaround:
import os, shutil
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
Note that it's not entirely consistent with the standard copytree
:
- it doesn't honor
symlinks
andignore
parameters for the root directory of thesrc
tree; - it doesn't raise
shutil.Error
for errors at the root level ofsrc
; - in case of errors during copying of a subtree, it will raise
shutil.Error
for that subtree instead of trying to copy other subtrees and raising single combinedshutil.Error
.
Python 3.8 introduced the dirs_exist_ok
argument to shutil.copytree
:
Recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory. dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.
Therefore, with Python 3.8+ this should work:
import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo', dirs_exist_ok=True)