How to loop through files and rename them in Python

3.6k views Asked by At

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

2

There are 2 answers

0
Eli Bendersky On
  • 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.

0
hochl On

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.