Search code examples
pythonloopscsvexceptionindex-error

IndexError on iterating through CSV column


I'm new to python and I'm encountering an IndexError: list index out of range when running the below code. I just have an Excel spreadsheet as a .csv file and I would like to take the info from the cells and append it into an array. It prints the info I want, but it seems to fail when it hits the last row. The error tells me I went 1 past the number of rows but I'm not sure how that happens.

dates = []
with open('File.csv') as csvDataFile:
    readCSV = csv.reader(csvDataFile)
    for row in readCSV:
        print(row[1])
        dates.append(row[1])

Solution

  • Some of your rows appear to be empty/having 1 column only. You could either use a try-except brace, or an if check.


    Option 1
    EAFP, try-except

    for row in readCSV:
        try:
            print(row[1])
            dates.append(row[1])
        except IndexError:
            pass
    

    Option 2
    if condition check

    for row in readCSV:
        if row:
            print(row[1])
            dates.append(row[1])