[Tutor] Accessing columns of a CSV file
Adam Bark
adam.jtm30 at gmail.com
Wed Nov 17 15:05:59 CET 2010
On 17/11/10 13:59, Hanlie Pretorius wrote:
> 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]
> ...
>
You need to print the 2nd item of row not of the entire file ie "print
row[1]" not "print cr[1]".
HTH.
Adam.
More information about the Tutor
mailing list