On 7/10/06, Richard Querin <[EMAIL PROTECTED]> 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 shell).

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.

  -Arcege
--
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to