the_t_test_1
the_t_test_1

Reputation: 1263

Count number of row entires in specific column of csv with python

Let's say I have a file items.csv which has 3 columns of data but a different amount of rows in each column that are filled, e.g.:

ITEM1,ITEM2,ITEM3,
DATA,DATA,DATA,
DATA,,DATA
,,DATA

i.e. reading down, ITEM1 column has only 2 lines, ITEM2 has 1 entry and ITEM3 has three entries of data ("DATA").

How can I write a function for my python 2.7 script that will open items.csv and return the number of lines in a specific column?

Thanks in advance.

Upvotes: 1

Views: 1493

Answers (1)

pbaranay
pbaranay

Reputation: 585

csv.DictReader would do the trick:

   import csv

   def get_number_of_rows(filename, header):
      with open(filename) as f:
         reader = csv.DictReader(f)
         return sum([bool(row[header]) for row in reader])

Upvotes: 1

Related Questions