Recursive Directory Tree Copier with Symlink and Ignore Options

  • Share this:

Code introduction


This function recursively copies an entire directory tree, including directories and files, and can optionally copy symlinks as symlinks or files. It takes the source directory path, destination directory path, a boolean flag indicating whether to copy symlinks, and a list of glob patterns to match filenames to ignore as parameters.


Technology Stack : shutil, os

Code Type : Function

Code Difficulty : Intermediate


                
                    
import shutil
import random

def copytree(src, dst, symlinks=False, ignore=None):
    """
    Copy an entire directory tree rooted at 'src'. The destination directory, 'dst',
    must not already exist; it will be created as well as all necessary parent
    directories. The optional argument 'symlinks' is a boolean indicating whether
    symbolic links in the source directory should be copied as symlinks (default
    False), or as files (default True). The optional argument 'ignore' is a list of
    glob patterns used to match filenames in the source directory that should be
    ignored during the copy process.

    Args:
        src (str): The source directory to copy.
        dst (str): The destination directory where the source will be copied to.
        symlinks (bool): Whether to copy symlinks as symlinks or files.
        ignore (list of str): List of glob patterns to match filenames to ignore.

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