0

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

2
  • This seems like a case where there are random blank lines in your csv file before your end of file. a single if(row) check might do the trick Commented Aug 3, 2019 at 5:54
  • you can check his answer. stackoverflow.com/a/57335829/8824174 Commented Aug 3, 2019 at 6:28

2 Answers 2

1

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

Comments

0

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

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.