csv.reader length?

Larry Bates larry.bates at websafe.com
Fri May 25 18:41:47 EDT 2007


Peter Otten wrote:
> 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
> 

Did you try:

import crystal_ball

num_lines=crystal_ball(reader)

Sorry I couldn't resist.

-Larry



More information about the Python-list mailing list