[Python-Dev] A smarter shutil.copytree ?

Gustavo Carneiro gjcarneiro at gmail.com
Thu Apr 17 19:10:53 CEST 2008


On 17/04/2008, Tarek Ziadé <ziade.tarek at gmail.com> wrote:
>
> Hi,
>
> 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
> os.mkdir(target)
> 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):
>             continue
>         os.mkdir(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')):
>             continue
>         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.


I also think this is a good idea; I recently was forced to copy-paste and
modify shutil.copytree into a project because of this limitation.

Regards
>
> Tarek
>
> --
>
> Tarek Ziadé | Association AfPy | www.afpy.org
> Blog FR | http://programmation-python.org
> Blog EN | http://tarekziade.wordpress.com/
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe:
> http://mail.python.org/mailman/options/python-dev/gjcarneiro%40gmail.com
>



-- 
Gustavo J. A. M. Carneiro
INESC Porto, Telecommunications and Multimedia Unit
"The universe is always one step beyond logic." -- Frank Herbert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-dev/attachments/20080417/ffb2ca5b/attachment.htm 


More information about the Python-Dev mailing list