Python new user question - file writeline error
Jerry Hill
malaclypse2 at gmail.com
Wed Feb 7 18:07:17 EST 2007
On 7 Feb 2007 11:31:32 -0800, James <cityhunter007 at gmail.com> wrote:
> I have this code:
...
> infile.close
> outfile.close
...
> 1. the outfile doesn't complete with no error message. when I check
> the last line in the python interpreter, it has read and processed the
> last line, but the output file stopped before.
You need to call the close methods on your file objects like this:
outfile.close()
If you leave off the parentheses, you get the method object, but don't
do anything with it.
> 2. Is this the best way to do this in Python?
I would parse your dates using the python time module, like this:
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win32
IDLE 1.2
>>> import time
>>> line = r'06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/NOV/2006,V1,,,21/NOV/2006,AST,19,U/L,5,40,,'
>>> item = line.split(',')
>>> time.strftime('%a, %d %b %Y', timedate)
'Sun, 05 Mar 1950'
>>> dob = item[6]
>>> dob_time = time.strptime(dob, '%d/%b/%Y')
>>> dob_time
(1950, 3, 5, 0, 0, 0, 6, 64, -1)
>>> time.strftime('%Y-%m-%d', dob_time)
'1950-03-05'
See the docs for the time module here:
http://docs.python.org/lib/module-time.html
Using that will probably result in code that's quite a bit easier to
read if you ever have to come back to it.
You also might want to investigate the csv module
(http://docs.python.org/lib/module-csv.html) for a bunch of tools
specifically tailored to working with files full of comma separated
values like your input files.
--
Jerry
More information about the Python-list
mailing list