Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python csv question [duplicate]

Tags:

python

csv

i'm just testing out the csv component in python, and i am having some trouble with it.

I have a fairly standard csv string, and the default options all seems to fit with my test, but the result shouldn't group 1, 2, 3, 4 in a row and 5, 6, 7, 8 in a row?

Thanks a lot for any enlightenment provided!

Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) 
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> c = "1, 2, 3, 4\n 5, 6, 7, 8\n"
>>> test = csv.reader(c)
>>> for t in test:
...     print t
... 
['1']
['', '']
[' ']
['2']
['', '']
[' ']
['3']
['', '']
[' ']
['4']
[]
[' ']
['5']
['', '']
[' ']
['6']
['', '']
[' ']
['7']
['', '']
[' ']
['8']
[]
>>> 
like image 478
FurtiveFelon Avatar asked Jul 05 '09 02:07

FurtiveFelon


4 Answers

csv.reader expects an iterable. You gave it "1, 2, 3, 4\n 5, 6, 7, 8\n"; iteration produces characters. Try giving it ["1, 2, 3, 4\n", "5, 6, 7, 8\n"] -- iteration will produce lines.

like image 168
John Machin Avatar answered Nov 04 '22 13:11

John Machin


csv.reader takes an iterable or iterator returning lines, see the docs. You're passing it a string, which is an iterable returning single characters.

So, use csv.reader(c.splitlines()) or similar constructs!

like image 36
Alex Martelli Avatar answered Nov 04 '22 13:11

Alex Martelli


test = csv.reader(c.split('\n'))

like image 44
sunqiang Avatar answered Nov 04 '22 12:11

sunqiang


To make it more file-like try this.

import StringIO
c= StringIO.StringIO( "1, 2, 3, 4\n 5, 6, 7, 8\n" )

Now c looks like a file. A file is what you use with csv most (if not all) of the time.

like image 31
S.Lott Avatar answered Nov 04 '22 12:11

S.Lott