How can I get the row count of a CSV file?

14,696

Solution 1

just do

len(list(reader))

it iterates through the reader object to create a list, then computes length & the number or rows is the list length (title not included)

note that this statement consumes the file, so store the list(reader) variable somewhere if you plan to parse the file.

Solution 2

An efficient way to get row count using sum function(with a generator expression):

with open('names.csv') as csvfile:
    row_count = sum(1 for row in csvfile)
    print(row_count if row_count else 'Empty')
Share:
14,696
TmX GordioN REKT
Author by

TmX GordioN REKT

Updated on July 13, 2022

Comments

  • TmX GordioN REKT
    TmX GordioN REKT almost 2 years
    fieldnames = ['first_name', 'last_name', 'address']
    with open('names.csv') as csvfile:
        reader = csv.DictReader(csvfile, fieldnames=fieldnames)
        for row in reader:
            print(row['first_name'], "'s number", row['last_name'], "address", row['adres'])
    

    This is my code to print my CSV file. If the CSV file is empty, I want to print that it's empty. I thought that if i can get the row count of the file, I can check if it's empty.