Fwd: Python new user question - file writeline error
James
cityhunter007 at gmail.com
Thu Feb 8 16:16:19 EST 2007
On Feb 8, 3:26 pm, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> 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.
No offense - but the fact that 're' module is available, doesn't that
mean we can use it? (Pythonic or not - not sure what is really
pythonic at this stage of learning...)
Like Perl, I'm sure there are more than one way to solve problems in
Python.
I appreciate everyone's feedback - I definitely got more than
expected, but it feels comforting that people do care about writing
better codes! :)
More information about the Python-list
mailing list