Fwd: Python new user question - file writeline error

Shawn Milo Shawn at Milochik.com
Thu Feb 8 12:20:57 EST 2007


On 8 Feb 2007 09:05:51 -0800, Gabriel Genellina <gagsl-py at yahoo.com.ar> wrote:
> On 8 feb, 12:41, "Shawn Milo" <S... at Milochik.com> wrote:
>
> > 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.
>
> A few comments:
>
> You don't need the formatDatePart function; delete it, and replace
> newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum)
> with
> newDate = ",%04.4d-%02.2d-%02.2d," % (yearNum,monthNum,dayNum)
>
> and before:
>                 dayNum, monthNum, yearNum = [int(num) for num in
> someDate[1:-1].split('/')]
>
> And this: outfile.writelines(line)
> should be: outfile.write(line)
> (writelines works almost by accident here).
>
> You forget again to use () to call the close methods:
> infile.close()
> outfile.close()
>
> I don't like the final replace, but for a script like this I think
> it's OK.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Gabriel,

Thanks for the comments! The new version is below. I thought it made a
little more sense to format the newDate = ... line the way I have it
below, although I did incorporate your suggestions. Also, the
formatting options you provided seemed to specify not only string
padding, but also decimal places, so I changed it. Please let me know
if there is some other meaning behind the way you did it.

As for not liking the replace line, what would you suggest instead?

Shawn

#! /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')

regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},")

for line in infile:
        matches = regex.findall(line)
        for someDate in matches:

                dayNum = someDate[1:3]
                monthNum = month[someDate[4:7]]
                yearNum = someDate[8:12]

                newDate = ",%04d-%02d-%02d," %
(int(yearNum),int(monthNum),int(dayNum))
                line = line.replace(someDate, newDate)

        outfile.write(line)

infile.close()
outfile.close()



More information about the Python-list mailing list