[Tutor] How can I copy files recursively?

Michael P. Reilly arcege at gmail.com
Tue Jul 11 16:24:13 CEST 2006

On 7/10/06, Richard Querin <rfquerin at gmail.com> wrote:
> I know this is probably a dumb question:
> I've got mp3 files that are downloaded (by ipodder) into individual
> subfolders. I'd like to write a quick script to move (not copy) all the mp3
> files in those folders into a single destination folder. I was thinking I
> could do it easily from the linux command line (cp -r copies the subfolders
> out as well) but I can't figure out how to do it. Is there an easy way to
> achieve this using Python? I am assuming this would be something Python was
> designed to make easy..
Python makes things easy, from a certain point of view.  You have to think
that Python is a program language and not a command language (like Bourne

Others have a number of solutions that will move your files with os.walk and
os.path.walk.  They are nice, but sometimes it's better to traverse the tree
individually.  Also, you didn't specify if the destination "folder"
structure already existed, or if it will need to be created (which cp -r
will do).  The following should handle that case for you:

import fnmatch, os
def movetree(srcdir, dstdir, pattern=None):
    # dstdir must exist first
    srcnames = os.listdir(srcdir)
    for name in srcnames:
        srcfname = os.path.join(srcdir, name)
        dstfname = os.path.join(dstdir, name)
        if os.path.isdir(srcfname):
            os.mkdir(dstfname, 00)
            movetree(srcfname, dstfname)
        elif pattern is None or fnmatch.fnmatch(name, pattern):
            os.rename(srcfname, dstfname)

You could do the same with os.walk or os.path.walk, but the recursive nature
of the function takes care of itself a bit better, IMO.

There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060711/eb4e8fb4/attachment.html 

More information about the Tutor mailing list