parse a csv file into a text file

MRAB python at mrabarnett.plus.com
Thu Feb 6 08:16:37 EST 2014


On 2014-02-06 07:52, Zhen Zhang wrote:> 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
 >
"line" is a list and within repr you're using (...) (parentheses)
instead of [...] (square brackets).

It might be clearer if you call the variable "row" because the CSV
reader returns rows, and each row is a list of strings.

 > 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))
 >
A 1-tuple (a tuple containing one item) is:

     (item, )

It's actually the comma that makes it a tuple (except for the 0-tuple
"()"); it's just that it's often necessary to wrap it in (...), and
people then think it's those that are making it a tuple, but it's not!

 > 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.
 >
What is the value of "line" at that point?



More information about the Python-list mailing list