Python new user question - file writeline error

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Feb 7 15:27:58 EST 2007


James a écrit :
> Hello,
> 
> I'm a newbie to Python & wondering someone can help me with this...
> 
> I have this code:
> --------------------------
> #! /usr/bin/python
> 
> import sys
> 
> 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')
> 
> for line in infile:
>     item = line.split(',')

CSV format ?
http://docs.python.org/lib/module-csv.html

>     dob = item[6].split('/')
>     dob = dob[2]+'-'+str(month[dob[1]])+'-'+dob[0]

Why did you use integers as values in the month dict if it's for using 
them as strings ?

>     lbdt = item[8].split('/')
>     lbdt = lbdt[2]+'-'+str(month[lbdt[1]])+'-'+lbdt[0]
>     lbrc = item[10].split('/')
>     lbrc = lbrc[2]+'-'+str(month[lbrc[1]])+'-'+lbrc[0]
>     lbrp = item[14].split('/')
>     lbrp = lbrp[2]+'-'+str(month[lbrp[1]])+'-'+lbrp[0]

This may help too:
http://docs.python.org/lib/module-datetime.html

>     item[6] = dob
>     item[8] = lbdt
>     item[10]=lbrc
>     item[14]=lbrp
>     list = ','.join(item)

Better to avoid using builtin types names as identifiers. And FWIW, this 
is *not* a list...

>     outfile.writelines(list)

You want file.writeline() or file.write(). And you have to manually add 
the newline.

> infile.close

You're not actually *calling* infile.close - just getting a reference on 
the file.close method. The parens are not optional in Python, they are 
the call operator.

> outfile.close

Idem.

> -----------------------------
> 
> And the data file(TVA-0316) looks like this:
> -----------------------------
> 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,,
> 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/
> NOV/2006,V1,,,21/NOV/2006,GGT,34,U/L,11,32,h,
> 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/
> NOV/2006,V1,,,21/NOV/2006,ALT,31,U/L,5,29,h,
> 06-0588,03,701,03701,0000046613,JJB,05/MAR/1950,M,20/NOV/2006,08:50,21/
> NOV/2006,V1,,,21/NOV/2006,ALKP,61,U/L,40,135,,
> -----------------------------
> 
> Basically I'm reading in each line and converting all date fields (05/
> MAR/1950) to different format (1950-03-05) in order to load into MySQL
> table.
> 
> I have two issues:
> 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.

Use the csv module and cleanly close your files, then come back if you 
still have problems.

> 2. Is this the best way to do this in Python?

Err... What to say... Obviously, no.



More information about the Python-list mailing list