Reputation: 11
I am trying to find few items from a CSV file when I run the code sometimes it works but sometimes it produces error list index out of range
def find_check_in(name,date):
x = 0
f = open('employee.csv','r')
reader = csv.reader(f, delimiter=',')
for row in reader:
id = row[0]
dt = row[1]
v = row[2]
a = datetime.strptime(dt,"%Y-%m-%d")
if v == "Check-In" and id=="person":
x = 1
f.close()
return x
Traceback (most recent call last):
File "", line 51, in x=find_check_in(name,date)
File "", line 21, in find_check_in id = row[0]
IndexError: list index out of range
Upvotes: 0
Views: 101
Reputation: 81
Seems like reader is returning a row with no elements. Does your data contain any such rows? Or perhaps you need to use the newline=''
argument to reader
?
https://docs.python.org/3/library/csv.html#csv.reader
Upvotes: 0
Reputation: 106793
Your CSV file contains blank lines, resulting in row
becoming an empty list, in which case there is no index 0, hence the error. Make sure your input CSV has no blank line, or add a condition to process the row only if it isn't empty:
for row in reader:
if row:
# the rest of your code
Upvotes: 1