Friday, September 2, 2011

Simple python issues

This post will list some simple python issues that I always have to look up.

To build a string showing a number with a percent sign, use: "%f%%" % some_float

To swap values: a,b = b,a

The three ways of building a path string:
'D:\\Temp\\temp.txt', r'D:\Temp\temp.txt', 'D:/Temp/temp.txt'
(Note: I think Python converts all three to the first one, so splitting on "\\" seems to work best)

To traverse all sub-folders and files of a workspace, use:
for root, subs, files in os.walk(workspace)

To calculate DOY from a datetime object:
from datetime import datetime
dt_obj =
doy = dt_obj.timetuple().tm_yday

Regular expression to "match all": '.*' or '.*?'
Regular expression to "match nothing": 'a^'