[Tutor] CSV module?

Liam Clarke cyresse at gmail.com
Sun Nov 21 02:26:43 CET 2004


Hi all,

Trying to work the CSV module, and I'm not quite sure how to
input/output through it.

I've worked out to output a CSV file that looks like - 

A B C
1  2 3
4  5 6

you have to use a list like this -
spreadS=[['A','B','C'],[1,2,3],[4,5,6]], so each row is a separate
list.

and then 

dave=file('test.csv', 'w')
henry=csv.writer(dave)

and either

for element in dave:
    henry.writerow(element)

or just

henry.writerows(dave).

So writing is fine. But, if I were to reopen test.csv - 

x=file('test.csv','r')

I can do this - 

>>> print x.readlines()
['A,B,C\r\n', '1,2,3\r\n', '4,5,6\r\n']

which is roughly what I expected.

Howeever, if I were to do - 

>>>bob=csv.reader(x)

And as per the Python docs - 

for element in bob:
     print element

I get nothing.

If I try bob.next(), I get 'StopIteration' which means that it's
reached the end of the file.

So help? I'm probably doing something quite simple & silly, but the
documentation isn't much help (to me), and I've got not spreadsheet
software installed on this comp to check that my csv's are valid.

I figure if I can pipe some data out through the CSV module and then
pipe it back in and nothing's changed then I'm doing OK.

Regards,

Liam Clarke

-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list