Friday, August 26, 2011

Python file renamer!

Sometimes we may want to remove some common patterns from files. For example, if we download MP3 songs or music from a specific website, then all the file names will begin with that website name. This might create some irritation when searching for songs. The following snippet of Python can be used to rename files in directory and to remove common patterns from files.

This is applicable to all types of files and just not limited to mp3 files.

import os, array
files = os.listdir("D:\\Music") #The directory path of the files goes here
fnames = array.array('u')
fnames = files
#print fnames
#print files
for filename in fnames:
    print filename
    if(filename.startswith("<text to remove>")): # The common pattern that you want to remove goes within the quotes
        print "Found: " + filename
        os.rename(filename,filename.replace(("
<text to remove>"),"<If left empty the pattern will be removed with remaining text a new filename, or type something to replace the common pattern>"))
        print "Renamed to: " + filename.replace("_","")
 
print "Finished task"
This shows the simplicity of Python language and also its ability to achieve something tedious with much shorter codes. Although it lacks performance, it can be effectively used to write this kind of codes that will make our tasks easier.



No comments:

Post a Comment

Your Ad Here