Last Updated: February 25, 2016
· bassemdy

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):

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])


shutil.copytree(src, dst, symlinks=False, ignore=None)

shutil.copytree() has a filter implementation which is triggered with its argument: ignore

Further readings:
Miscellaneous operating system interfaces:

Core Distutils functionality:

High-level file operations: