Python directory traversal & copying
I needed to copy an entire folder structure without the files to a new target directory. Below is the code:
# Recreate all path directories & subdirectories
# ignoring files
def directory_mirror(originalPath, targetPath):
for root, subFolders, files in os.walk(originalPath):
newDir = os.path.join(targetPath, root[1+len(originalPath):])
# Make sure the path doesn't already exist
# or the function makedirs will throw an
# exception
if not os.path.exists(newDir):
os.makedirs(newDir)
If you wish to copy an entire tree to an new directory, you can either use:
distutils.dir_util.copy_tree(src, dst[, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0])
http://docs.python.org/2/distutils/apiref.html#module-distutils.dir_util
or
shutil.copytree(src, dst, symlinks=False, ignore=None)
http://docs.python.org/2/library/shutil.html
shutil.copytree() has a filter implementation which is triggered with its argument: ignore
Further readings:
Miscellaneous operating system interfaces: http://docs.python.org/2/library/os.html
Core Distutils functionality: http://docs.python.org/2/distutils/apiref.html#module-distutils.core
High-level file operations:
http://docs.python.org/2/library/shutil.html
Written by Bassem Dy
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#