Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python copytree with negated ignore pattern

Tags:

python

regex

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.

like image 424
Chris H Avatar asked May 12 '10 18:05

Chris H


2 Answers

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)
like image 119
unutbu Avatar answered Oct 04 '22 23:10

unutbu


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/*')
like image 35
johntellsall Avatar answered Oct 04 '22 23:10

johntellsall