How do I copy an entire directory of files into an existing directory using Python?
The shutil
and os
modules in Python provide means to copy files and directories including their metadata (file attributes), to an existing directory:
All files and subdirectories in /source/dir
will be copied into /target/existing/dir
while also preserving the original attributes of the files.
Beyond the basic: Exceptional conditions and Python versions
Workaround for Python < 3.8
OSError
likes to crash the party if your Python version < 3.8. The copy_tree
function from the distutils.dir_util
module can help you handle that:
Playing nice with symlinks and permissions
Look out for symlinks and file permissions while copying. You don't want to leave anything behind:
Catch errors while they last
Preferred way to handle errors like a pro is to catch the returned shutil.Error
:
Various scenarios when copying directories
Selective updates: only fresh gets served
Updating files selectively, like careful chefs adding seasoning to a dish:
Use this function instead of shutil.copy2
in recursive_copy
.
Strictly subdirectories: Files need not apply
If you don't want to copy top-level files but only subdirectories, filter them out:
Copying and applying file status metadata
For those wanting an exact replica, use shutil.copystat
after copying to apply metadata:
Was this article helpful?