How to loop through files and rename them in Python
Asked Answered
A

2

5

I have a directory of music that has album folders as well as individual songs on each level. How can I traverse all of these files that also are encoded in different formats(mp3, wav etc)? In addition is there a way I can rename them to a format that is more consistent to my liking using regular expressions?

Thanks

Anna answered 25/10, 2011 at 19:5 Comment(5)
I usually charge money to code up something like that. Here's something similar that I wrote in perl, you can at least see the rough idea: github.com/eberle1080/oggsyncExtemporary
@Chris: ouch, 300 lines of Perl to traverse and rename files?Larry
No, 300 lines to transcode from one format to another. Isn't this what the OP was after?Extemporary
@Chris: I think you should read the question :)Larry
Yeah, whoops. My bad. I read into that incorrectly.Extemporary
L
7
  • os.walk to go over files in the directory and its sub-directories, recursively
  • os.rename to rename them

The encoding of the files pays no role here, I think. You can, of course, detect their extension (use os.path.splitext for that) and do something based on it, but as long as you just need to rename files (i.e. manipulate their names), contents hardly matter.

Larry answered 25/10, 2011 at 19:10 Comment(0)
C
1

I use this piece of code in a program I wrote. I use it to get a recursive list of image files, the call pattern is something like re.compile(r'\.(bmp|jpg|png)$', re.IGNORECASE). I think you get the idea.

def getFiles(dirname, suffixPattern=None):
        dirname=os.path.normpath(dirname)

        retDirs, retFiles=[], []
        for root, dirs, files in os.walk(dirname):
                for i in dirs:
                        retDirs.append(os.path.join(root, i))
                for i in files:
                        if suffixPattern is None or \
                           suffixPattern.search(i) is not None:
                                retFiles.append((root, i))

        return (retDirs, retFiles)

After you have the list, it would be easy to apply a renaming rule. os.rename is your friend, see http://docs.python.org/library/os.html.

Cartagena answered 25/10, 2011 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.