Monday, February 2, 2009

Snippets: Filename padder [Python]

I recently downloaded nearly 1400 pictures (a complete webcomic). The problem came with the naming. The files were named from 1.png to 1400.png, making CDisplay and other programs display them in ASCII sort (1.png, 10.png, 100.png, 1000.png, 2.png...). Maybe there is a better solution but what I did was pad the filenames with zeros, so they became 0001.png, 0010.png and so.

This is what I did:
  1. import os  
  2.   
  3. dir = "D:\\Directory\\"  
  4. for file in os.listdir(dir):  
  5.  splitfilename = file.split(".")  
  6.  name = splitfilename[0]  
  7.  extension = splitfilename[1]  
  8.   
  9.  newname = "0" * (4 - len(name)) + name  
  10.  print file + " => " + newname + "." + extension  
  11.  os.rename(dir + file, dir + newname + "." + extension  

No comments:

Post a Comment

Please, be polite and constructive.