-1

I tried to parse a csv file to obtain the number of the columns and print out information from the column 2.

Below is my code and output:


>>>import csv
>>>with open('test.1.csv','r') as infile:
...     text=csv.reader(infile,delimiter=',', quotechar='|')
...     fields=len(list(text)[0])
...     print fields
...     for row in text:
...             print row[1]

5

My question is why I only got number of the columns, but not the content of column 2?

Thank you very much for any inputs:)

lotfio
  • 1,916
  • 2
  • 18
  • 34

1 Answers1

0

Because the reader object that the variable text is was already used in len(list(text)[0]).

A Reader (similar to an Iterator) only returns all lines in a file once. It does this, when you use list(text).

You can rewrite your code in this way and it will work:

>>>import csv
>>>with open('test.1.csv','r') as infile:
...     text=list(csv.reader(infile,delimiter=',', quotechar='|'))
...     fields=len(text[0])
...     print fields
...     for row in text:
...             print row[1]
Semmel
  • 575
  • 2
  • 8