[Python-Dev] A smarter shutil.copytree ?

Tarek Ziadé ziade.tarek at gmail.com
Thu Apr 17 18:52:34 CEST 2008


shutil.copytree is very convenient to make recursive copies, but
os.walk has to be used everytime some filtering
has to be done on the files copied., if you want to avoid copying some files.

The code pattern with os.walk is pretty talkative :

--------------------- copying a source folder to a target folder, but
the pyc/pyo files
for root, dirs, filenames in os.walk(source):
    root_target = root.replace(source, target)
    for dir_ in dirs:
        target_dir = join(root_target, dir_)
        if os.path.exists(target_dir):
    for filename in filenames:
        filename_source = join(root, filename)
        filename_target = join(root_target, filename)
        if (os.path.exists(filename_target) or
            os.path.splitext(filename) in ('.pyc', '.pyo')):
        shutil.copyfile(filename_source, filename_target)

If we could provide a callable argument to shutil.copytree, this would
allow simplifying a lot the code:

--------------------- copying a source to a target, but the pyc/pyo file
def filtering(source, target):
    return os.path.splitext(filename) not in ('.pyc', '.pyo')

shutil.copytree(source, target, filter_=filtering)

This is a very current pattern in my code, and I think this could be
an interesting enhancement to
shutil. So if people think it is a good idea, I can work on a patch
and submit it to the tracker.



Tarek Ziadé | Association AfPy | www.afpy.org
Blog FR | http://programmation-python.org
Blog EN | http://tarekziade.wordpress.com/

More information about the Python-Dev mailing list