parse a csv file into a text file

Tim Chase python.list at
Thu Feb 6 01:46:04 CET 2014

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:


rather than trying to do it all in one pass.


More information about the Python-list mailing list