Number of cells, using CSV module

T

tunacubes

I'm using the csv module to get information from a csv file. I have items listed in Column A. I want to know how many items are listed in Column A.

import csv
with open('test.csv', 'r') as f:
reader = csv.reader(f)
for column in reader:
column = (column[0])
print(column)

We are given
a
b
c
d
e
f

How would I go about getting the amount of numbers that are printed? If I try printing len(column), I get
 
S

Skip Montanaro

Perhaps you want len(reader) instead? Or a counter which increments for
every row read which has an item in column A?

Skip
 
T

tunacubes

Perhaps you want len(reader) instead?  Or a counter which increments for every row read which has an item in column A?



Skip

len(reader) gives me an error.

I tried a counter, but unfortunately due to the simplicity of CSV files, any formulas are not saved.
 
T

tunacubes

I guess another way to accomplish this would be, is there any way that I can turn the returned value for (column) into 1 list?

So rather than
a
b
c
d
e
f
I would get [a, b, c, d, e, f]
 
S

Skip Montanaro

len(reader) gives me an error.

Apologies. len(list(reader)) should work. Of course, you'll wind up
loading the entire CSV file into memory. You might want to just count
row-by-row:

n = 0
for row in reader:
n += 1

Skip
 
T

Tim Chase

Apologies. len(list(reader)) should work. Of course, you'll wind
up loading the entire CSV file into memory. You might want to just
count row-by-row:

n = 0
for row in reader:
n += 1

which can nicely be rewritten as

n = sum(1 for row in reader)

:)

-tkc
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top