Chris H Chris H - 1 year ago 78
Python Question

python copytree with negated ignore pattern

I'm trying to use python to copy a tree of files/directories.

is it possible to use copytree to copy everything that ends in foo?

There is an ignore_patterns patterns function, can I give it a negated regular expression? Are they supported in python?


copytree(src, dest, False, ignore_pattern('!*.foo'))
Where ! means NOT anything that ends in foo.

Answer Source

shutil.copytree has an ignore keyword. ignore can be set to any callable. Given the directory being visited and a list of its contents, the callable should return a sequence of directory and filenames to be ignored.

For example:

import shutil
def ignored_files(adir,filenames):
    return [filename for filename in filenames if not filename.endswith('foo')]

shutil.copytree(source, destination, ignore=ignored_files)