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?
eg.
copytree(src, dest, False, ignore_pattern('!*.foo')) Where ! means NOT anything that ends in foo. thanks.
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)
Building on unutbu's answer. The following takes a list of all files, then removes the ones matched by "ignore_patterns", then returns that as a list of files to be ignored. That is, it does a double negation to only copy the files you want.
import glob, os, shutil
def copyonly(dirpath, contents):
return set(contents) - set(
shutil.ignore_patterns('*.py', '*.el')(dirpath, contents),
)
shutil.copytree(
src='.',
dst='temp/',
ignore=copyonly,
)
print glob.glob('temp/*')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With