3
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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
TmX GordioN REKT
  • 95
  • 2
  • 3
  • 7
  • Possible duplicate of [Number of lines in csv.DictReader](https://stackoverflow.com/questions/2890549/number-of-lines-in-csv-dictreader) – Abhijeet Jun 20 '17 at 11:49

4 Answers4

10

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')
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
8

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

What about this :

import os
os.stat("names.csv").st_size == 0

Return true if it's empty, you want this right?

0

You could also enumerate the entries as you parse the file as follows:

fieldnames = ['first_name', 'last_name', 'address']

with open('names.csv') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames=fieldnames)
    for count, row in enumerate(reader):
        print(row['first_name'], "'s number", row['last_name'], "address", row['address'])            

    if count == 0:
        print("empty")
Martin Evans
  • 45,791
  • 17
  • 81
  • 97