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:

import os

dir = "D:\\Directory\\"
for file in os.listdir(dir):
splitfilename = file.split(".")
name = splitfilename[0]
extension = splitfilename[1]

newname = "0" * (4 - len(name)) + name
print file + " => " + newname + "." + extension
os.rename(dir + file, dir + newname + "." + extension

No comments:

Post a Comment

Please, be polite and constructive.