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.

1

4 Answers 4

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')
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

In practice, I had to open file once to get row count, close it, open again and parse it normally.
Yes it works, but it's much better to read the file once and store it in memory (unless the file is super huge and doesn't hold in memory)
0

What about this :

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

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

1 Comment

if there's only a title line, that would fail.
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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.