问题
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:
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:
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')
回答3:
What about this :
import os
os.stat("names.csv").st_size == 0
Return true if it's empty, you want this right?
回答4:
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")
来源:https://stackoverflow.com/questions/41553467/how-can-i-get-the-row-count-of-a-csv-file