csv.reader length?

C

cjl

P:

Stupid question:

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?

-CJL
 
7

7stud

P:

Stupid question:

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?

-CJL

How about:

f = open("somefile.csv")
numlines = len(f.readlines())
 
P

Peter Otten

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
 
L

Larry Bates

Peter said:
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
 
J

John Machin

P:

Stupid question:

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?

-CJL

Of course not. A CSV file (even without the embedded newline
complication mentioned by Peter) is a file of variable-length records
separated by a one-or-two-character sequence. Modern Python-supported
filesystems' directories don't keep the information that would be
required to tell you whether a file's records are fixed or variable
length, let alone how many "records" there are in a file.

Why are you asking? Perhaps if you tell us what you are trying to
achieve, we can help you.

Cheers,
John
 
P

Peter Otten

Larry said:
Did you try:

import crystal_ball

num_lines=crystal_ball(reader)

Yes. The answer was a little more comprehensive than I had asked for.
42

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,006
Latest member
LauraSkx64

Latest Threads

Top