Fwd: Python new user question - file writeline error
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Thu Feb 8 15:26:26 EST 2007
Shawn Milo a écrit :
> 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:
>
>
> #! /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"
> x = str(x)
> while len(x) < 2:
> x = "0" + x
> return x
x = "%02d" % x
> regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},")
regexps are not really pythonic - we tend to use them only when we have
no better option. When it comes to parsing CSV files and/or dates, we do
have better solution : the csv module and the datetime module....
> for line in infile:
> matches = regex.findall(line)
> for someDate in matches:
>
> dayNum = formatDatePart(someDate[1:3])
> monthNum = formatDatePart(month[someDate[4:7]])
> yearNum = formatDatePart(someDate[8:12])
>
> newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum)
> line = line.replace(someDate, newDate)
> outfile.writelines(line)
>
> infile.close
> outfile.close
I wonder why some of us took time to answer your first question. You
obviously forgot to read these answers.
More information about the Python-list
mailing list