parse a csv file into a text file

Zhen Zhang zhen.zhang.uoft at gmail.com
Thu Feb 6 09:07:29 CET 2014


On Wednesday, February 5, 2014 7:46:04 PM UTC-5, Tim Chase wrote:
> On 2014-02-05 16:10, Zhen Zhang wrote:
> 
> > import csv
> 
> > file = open('raw.csv')
> 
> 
> 
> Asaf recommended using string methods to split the file.  Keep doing
> 
> what you're doing (using the csv module), as it attends to a lot of
> 
> edge-cases that will trip you up otherwise.  I learned this the hard
> 
> way several years into my Python career. :-)
> 
> 
> 
> > reader = csv.reader(file)
> 
> > 
> 
> > f = open('NicelyDone.text','w')
> 
> > 
> 
> > for line in reader:
> 
> >       f.write("%s %s"%line[1],%line[5])
> 
> 
> 
> Here, I'd start by naming the pieces that you get, so do
> 
> 
> 
>   for line in reader:
> 
>     location = line[1]
> 
>     value = line[5]
> 
> 
> 
> > Also, I have to process the first column eg, "Toronto (Ont.)" into
> 
> > "Toronto". I am familiar with the function find(), I assume that i
> 
> > could extract Toronto out of Toronto(Ont.) using "(" as the
> 
> > stopping character, but based on my research , I have no idea how
> 
> > to use it and ask it to return me the string(Toronto).
> 
> 
> 
> You can use the .split() method to split a string, so you could do
> 
> something like
> 
> 
> 
>   if '(' in location:
> 
>     bits = location.split('(')
> 
>     # at this point, bits = ['Toronto ', 'Ont.)']
> 
>     location = bits[0].strip() # also strip it to remove whitespace
> 
> 
> 
> > 1:What is the data format for line[1], if it is string how come
> 
> > f.write()does not work. if it is not string, how do i convert it to
> 
> > a string?
> 
> 
> 
> The problem is not that "it is not a string" but that you passing
> 
> multiple parameters, the second of which is invalid Python because it
> 
> has an extra percent-sign.  First create the one string that you
> 
> want to output:
> 
> 
> 
>   output = "%s %s\n" % (location, bits)
> 
> 
> 
> and then write it out to the file:
> 
> 
> 
>   f.write(output)
> 
> 
> 
> rather than trying to do it all in one pass.
> 
> 
> 
> -tkc

Hi Tim,

Thanks for the reply,

Does the split make a list or tuple?

also,

when  i do location=line[1],
it gives me a error even though the program did run correctly and output the correct file.
 location=line[1]
 IndexError: list index out of range 

when i do print line[1], there is no error.
it is really strange



More information about the Python-list mailing list