Shawn Milo kirjoitti: > To the list: > > I have come up with something that's working fine. However, I'm fairly > new to Python, so I'd really appreciate any suggestions on how this > can be made more Pythonic. > > Thanks, > Shawn > > > > > > > Okay, here's what I have come up with:
What follows may feel harsh but you asked for it ;) > > > #! /usr/bin/python > > import sys > import re > > month > ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12} > > > infile=file('TVA-0316','r') > outfile=file('tmp.out','w') > > def formatDatePart(x): > "take a number and transform it into a two-character string, > zero padded" If a comment or doc string is misleading one would be better off without it entirely: "take a number": the function can in fact take (at least) any base type "transform it": the function doesn't transform x to anything although the name of the variable x is the same as the argument x "two-character string": to a string of at least 2 chars "zero padded": where left/right??? > x = str(x) > while len(x) < 2: > x = "0" + x You don't need loops for these kind of things. One possibility is to replace the whole body with: return str(x).zfill(2) > return x > > regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},") > > for line in infile: > matches = regex.findall(line) > for someDate in matches: > Empty lines are supposed to make code more readable. The above empty line does the contrary by separating the block controlled by the for and the for statement > dayNum = formatDatePart(someDate[1:3]) > monthNum = formatDatePart(month[someDate[4:7]]) > yearNum = formatDatePart(someDate[8:12]) You don't need the formatDatePart function at all: newDate = ",%4s-%02d-%2s," % \ (someDate[8:12],month[someDate[4:7]],someDate[1:3]) > > newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum) > line = line.replace(someDate, newDate) > > outfile.writelines(line) > > infile.close > outfile.close You have not read the answers given to the OP, have you. Because if you had, your code would be: infile.close() outfile.close() The reason your version seems to be working, is that you probably execute your code from the command-line and exiting from Python to command-line closes the files, even if you don't. Cheers, Jussi -- http://mail.python.org/mailman/listinfo/python-list