Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through files and rename them in Python

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

like image 441
Christopher Hall Avatar asked Oct 25 '11 19:10

Christopher Hall


2 Answers

  • 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.

like image 156
Eli Bendersky Avatar answered Sep 24 '22 14:09

Eli Bendersky


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.

like image 30
hochl Avatar answered Sep 24 '22 14:09

hochl