Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

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

Tuesday, January 27, 2009

Snippets: Creating a matrix in python

There's two easy ways to do this:

Looping:

def matrix(rownumber,columnumber):
matrix = []
for i in range(rownumber):
a = [0]*columnumber
matrix.append(a)
return matrix


List comprehensions:

def matrix(rownumber, columnumber):
return [[0]*columnumber for x in range(rownumber)]