Custom Filter-Enabled Directory Copy Function

  • Share this:

Code introduction


This function extends shutil.copytree and allows the user to exclude certain files or directories using a custom filter before copying the directory tree.


Technology Stack : shutil, os

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import shutil
import random

def copytree_with_custom_filter(src, dst, symlinks=False, ignore=None):
    """
    Copy a directory tree rooted at 'src' to a new location 'dst'.

    This function is similar to shutil.copytree but includes a custom filter
    that allows for excluding certain files or directories based on a predicate.
    """
    if ignore is None:
        ignore = lambda x: False

    for item in shutil.listdir(src):
        if ignore(item):
            continue
        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: