csv.reader length?

Peter Otten __peter__ at web.de
Fri May 25 16:09:43 EDT 2007


7stud wrote:

> On May 25, 12:49 pm, cjl <cjl... at gmail.com> wrote:

>> reader = csv.reader(open('somefile.csv'))
>> for row in reader:
>>     do something
>>
>> Any way to determine the "length" of the reader (the number of rows)
>> before iterating through the rows?

No. You have to read the records to know the length:

rows = list(reader)
print len(rows)
for row in rows:
    # ...

> How about:
> 
> f = open("somefile.csv")
> numlines = len(f.readlines())

No, a field in a csv file may contain newlines:

>>> import csv
>>> csv.writer(open("tmp.csv", "w")).writerows([["a", "b\nc"], ["d", "e"]])
>>> len(open("tmp.csv").readlines())
3 # number of lines
>>> len(list(csv.reader(open("tmp.csv"))))
2 # number of records

Peter




More information about the Python-list mailing list