Exclude some of subfolders while copying (im using copytree) in python

Question:

I am trying to implement a DIR-COPY.
my input is like this..

    source = D/Test/Source
    Target = D/Test/Target
    Ignore_Pattern = '*.exe'
    Exclude_Sub_Folder = D/Test/Source/Backup,D/Test/Source/Backup2

I am able ignore .exe files using ignore property in copytree
Did like this

    shutil.copytree(source , Target ,ignore=shutil.ignore_patterns(Ignore_Pattern)) 

I am not sure how to exclude some of the subfolders in the source directory.

Please help…..

Thanks

Asked By: techrhl

||

Answers:

You can ignore all folders that have a name of Backup or Backup2:

shutil.copytree(source , Target ,ignore=shutil.ignore_patterns(Ignore_Pattern, "Backup", "Backup2"))

“But I have multiple folders named ‘Backup’ and I specifically want to ignore only the one in the Test/Source directory”, you say. In that case, you need to provide a custom ignoring function that investigates the full path.

to_exclude = ["D:/Test/Source/Backup", "D:/Test/Source/Backup2"]

#ignores excluded directories and .exe files
def get_ignored(path, filenames):
    ret = []
    for filename in filenames:
        if os.path.join(path, filename) in to_exclude:
            ret.append(filename)
        elif filename.endswith(".exe"):
            ret.append(filename)
    return ret

shutil.copytree(source , Target ,ignore=get_ignored)

(Take care in to_exclude to use the correct path separator for your particular OS. You don’t want “TestSourceBackup” getting included because you used the wrong kind of slash.)

Answered By: Kevin

better use platform independent PurePath. Paths = [".gitkeep","app/build"]

def callbackIgnore(paths):
    """ callback for shutil.copytree """
    def ignoref(directory, contents):
        arr = [] 
        for f in contents:
            for p in paths:
                if (pathlib.PurePath(directory, f).match(p)):
                    arr.append(f)
        return arr

    return ignoref
Answered By: Alexufo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.