[Tutor] manipulting CSV files

Lowell Tackett lowelltackett at yahoo.com
Fri Jan 8 15:54:59 CET 2010


>From the virtual desk of Lowell Tackett  



--- On Fri, 1/8/10, Kent Johnson <kent37 at tds.net> wrote:

> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] manipulting CSV files
> To: "Lowell Tackett" <lowelltackett at yahoo.com>
> Cc: "tutor" <Tutor at python.org>
> Date: Friday, January 8, 2010, 8:11 AM
> On Thu, Jan 7, 2010 at 1:26 PM,
> Lowell Tackett <lowelltackett at yahoo.com>
> wrote:
> > I found the Python documentation (on line} and came
> across--'csv.Dialect.skipinitialspace' 
> Try
> coord = csv.reader(open('true_coord', 'b'),
> skipinitialspace = True)
> 
> Note you should open the file in binary mode.
> 
> Kent
> 
I'm guessing the 'b' in the above code line refers to your recommendation to enlist binary mode.  Here's what Python thought of it:

>>> coord = csv.reader(open('true_coord', 'b'), skipinitialspace = True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: mode string must begin with one of 'r', 'w', 'a' or 'U', not 'b'

So, I put an 'r' in front of 'b', and it worked fine.

Now, perhaps you can you shed some light on this problem--I'm trying to do some simple arithmetic with two of the retrieved values, and get this error:

>>> coord = csv.reader(open('true_coord', 'rb'), skipinitialspace = True)
>>> for line in coord:
....  if line[0] == '1001':
....   print line
....
['1001', '342821.71900', '679492.08300', '0.00000', '']
....   print (int(line[1]) + int(line[2]))
....
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ValueError: invalid literal for int() with base 10: '342821.71900'

I tried:

....   print (line[1]) + (line[2])

But of course it did nothing but cat the two sequences.



      



More information about the Tutor mailing list