[Tutor] Accessing columns of a CSV file

Hanlie Pretorius hanlie.pretorius at gmail.com
Wed Nov 17 14:59:19 CET 2010


Hi,

I'm reading a CSV file and I want to test the contents of its second
column before I write it to an output file:

>>> import csv
>>> time_list=['00:00', '03:00', '06:00','09:00','12:00','15:00','18:00','21:00']
>>> readfile='C8R004_flow.csv'
>>> in_text=open(readfile,'rb')
>>> cr=csv.reader(in_text)
>>> cr
<_csv.reader object at 0x7f4dfc3b2360>
>>> for row in cr:
...     print row
['2005/01/31', '21:00:00', '26.508']
['2005/01/31', '21:12:00', '26.508']
['2005/01/31', '21:24:00', '26.508']
['2005/01/31', '21:36:00', '26.508']
['2005/01/31', '21:48:00', '26.508']
['2005/01/31', '22:00:00', '26.508']
['2005/01/31', '22:12:00', '26.508']
['2005/01/31', '22:24:00', '26.508']
['2005/01/31', '22:36:00', '26.508']
['2005/01/31', '22:48:00', '26.508']
['2005/01/31', '23:00:00', '26.508']
['2005/01/31', '23:12:00', '26.508']
['2005/01/31', '23:24:00', '26.508']
['2005/01/31', '23:36:00', '26.508']
['2005/01/31', '23:48:00', '26.508']
>>>

I would like to test the values in the second column to see if they're
in the list I named time_list and, if so, write the whole row to an
output file.

The problem is that I don't know how to access the second column of
values. I tried the direct route:
>>> for row in cr:
...     print cr[1]
...
>>>

and I've tried to convert the csv.reader object into a list:

[code]
>>> file_rows=[]
>>> for row in cr:
...     file_rows.append(row)
...
>>> file_rows
[]
[/code]

which clearly doesn't work.

Can someone perhaps suggest a method to access the value in the second
column of each row so that I can test it against the time_list?

Thanks
Hanlie


More information about the Tutor mailing list