Fwd: Python new user question - file writeline error
Gabriel Genellina
gagsl-py at yahoo.com.ar
Thu Feb 8 20:22:09 EST 2007
En Thu, 08 Feb 2007 14:20:57 -0300, Shawn Milo <Shawn at Milochik.com>
escribió:
> 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.
Looks pretty good for me!
Just one little thing I would change, the variables monthNum, dayNum etc.;
the suffix might indicate that they're numbers, but they're strings
instead. So I would move the int(...) a few lines above, where the
variables are defined.
But that's just a cosmetic thing and just a matter of taste.
> 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.
No, it has no meaning, at least for this range of values.
> As for not liking the replace line, what would you suggest instead?
You already have scanned the line to find the matching fragment; the match
object knows exactly where it begins and ends; so one could replace it
with the reformatted value without searching again, wich takes some more
time, at least in principle.
But this makes the code a bit more complex, and it would only make sense
if you were to process millions of lines, and even then, the execution
might be I/O-bound so you would gain nothing at the end.
That's why I think it's OK as it is now.
--
Gabriel Genellina
More information about the Python-list
mailing list