Thursday, February 16, 2012

batch rename and (move) files using python


So, my friend asked me to rename the files. The file names are alphanumeric and they should be renamed with leading zeroes but in order. the default sort is 1,10,11….2, 20….etc  but correct order would be 1,2,3,4,5…… So, I did some hit and trial and some binging, googling…
Finally done
here is the code

import os
import re
import shutil
 



def main():
## Commented out are the codes to create file for working purposes    
##    for a in range(1,20):
##        for b in ["a", "b", "c"]:
##            filename="sec"+str(a)+b+".data"
##            c=open(filename,"a")
##            c.close()
    directory="oldnames"
    directory2="newnames"
    fnames=os.listdir(directory)
    #print(str(fnames))
    sortedfnames=sorted(fnames, key=natural_sortkey)
    #print(str(sortedfnames))
    for index, fname in enumerate(sortedfnames):

        index2=str(index).zfill(4)  ##change zfill parameter to 3 if 001, 4 if 0001 etc
        #print str(index)+ fname
        shutil.copy(os.path.join(directory,fname), os.path.join(directory2,(index2+fname)))
    

tokenize = re.compile(r'(\d+)|(\D+)').findall

def natural_sortkey(string):          
    return tuple(int(num) if num else alpha for num, alpha in tokenize(string))


main()


Worked as magic!!



note: I got the alphanumeric sort tips from stackoverflow user(http://stackoverflow.com/users/107366/ants-aasma)

No comments:

Post a Comment