parse a csv file into a text file

Zhen Zhang zhen.zhang.uoft at gmail.com
Thu Feb 6 02:52:43 EST 2014


On Wednesday, February 5, 2014 7:33:00 PM UTC-5, Roy Smith wrote:
> In article <5c268845-003f-4e24-b27a-c89e9fbfcc6c at googlegroups.com>,
> 
>  Zhen Zhang <zhen.zhang.uoft at gmail.com> wrote:
> 
> 
> 
> > [code]
> 
> > 
> 
> > import csv
> 
> > file = open('raw.csv')
> 
> > reader = csv.reader(file)
> 
> > 
> 
> > f = open('NicelyDone.text','w')
> 
> > 
> 
> > for line in reader:
> 
> >       f.write("%s %s"%line[1],%line[5])
> 
> > 
> 
> > [/code]
> 
> 
> 
> Are you using Python 2 or 3?
> 
> 
> 
> > Here is my question:
> 
> > 1:What is the data format for line[1],
> 
> 
> 
> That's something you can easily figure out by printing out the 
> 
> intermediate values.  Try something like:
> 
> 
> 
> > for line in reader:
> 
> >       print type(line[1]), repr(line(1))
> 
> 
> 
> See if that prints what you expect.
> 
> 
> 
> > how come f.write() does not work.
> 
> 
> 
> What does "does not work" mean?  What does get written to the file?  Or 
> 
> do you get some sort of error?
> 
> 
> 
> I'm pretty sure I see your error, but I'm trying to lead you to being 
> 
> able to diagnose it yourself :-)

Hi Roy ,

Thank you so much for the reply,
I am currenly running python 2.7

i run the 
 print type(line[1]), repr(line(1)) 
It tells me that 'list object is not callable

It seems the entire line is a data type of list instead of a data type of "line" as i thought.

The line[1] is a string element of list after all.

f.write("%s %s %s" %(output,location,output))works great, 
as MRAB mentioned, I have to do write it in term of tuples.

This is the code I am currently using

for line in reader:
     location ="%s"%(line[1])
     if '(' in location:
        # at this point, bits = ['Toronto ', 'Ont.)'] 
        bits = location.split('(')  
        location = bits[0].strip()
     output = "%s %s\n" %(location,line[5])
     f.write("%s" %(output))

It extracts desired information into a text file as i wanted.
however, the python program gives me a Error after the execution.
 location="%s"%(line[1])
 IndexError: list index out of range

I failed to figure out why.



More information about the Python-list mailing list