Reputation: 129
I have a list of csv files : 'empty.csv' and 'headerOnly.csv' the first file is empty and the second only has one row (the header)
I'm trying to raise an exception when the file is empty and continue on when it only includes the header.
with open(csvfile, mode='rb') as csv_file:
#check for empty files
print(sum(1 for line in csv_file))#prints number of lines in file
if(sum(1 for line in csv_file) == 0):
print("csv file is empty")
elif(sum(1 for line in csv_file) == 1):
print( "only has header")
I know for a fact that the 'headerOnly.csv' file has ONE line and the first print statement validates that. Even if the print statment for 'headerOnly.csv' prints out 1, it never reaches the elif statement and even prints 'csv file is empty' for that file which is not.. not sure why it isn't reaching the elif
Upvotes: 0
Views: 63
Reputation: 781096
csv_file
is a generator of the lines in the file. The first time you loop through it, it reads all the lines. The second time, there are no more lines to read, so the loop returns 0
.
Save the result to a variable:
line_count = sum(1 for line in csv_file)
print(line_count)
if line_count == 0:
print("csv file is empty")
elif line_count == 1:
print("only has header")
And if you still want to read the file after this, you need to rewind:
csv_file.seek(0)
Upvotes: 3