简体   繁体   中英

Python CSV: IndexError: List Index out of range

I have very weird problem in working with csv. My code is :

        with open('CFD.csv', 'rt') as f:
            reader = csv.reader(f, delimiter=',')
            for row in reader:
                if cfd_number == row[0]:
                    cfd_checked_before = "Yes"

This code is working in Mac but in windows, I get the following error:

IndexError: List Index out of range

There are maybe some possible cases there...

  • Maybe you are opening a csv file in Windows not even alike as the csv file you are using in Mac
  • Maybe the problem there is in the line row[0]
  • Maybe your csv file does not contains any comma delimiter or some rows there has an empty line as stated.

try printing the row variable or even the reader variable

Its common to have empty lines in csv files, especially at the end of the file. If you want your code to accept this common error, just check the row list before use.

with open('CFD.csv', 'rt') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        if row:
            if cfd_number == row[0]:
                cfd_checked_before = "Yes"

You can also use filter for the same task. When its first parameter is None, it removes "falsey" things like empty lists:

with open('CFD.csv', 'rt') as f:
    reader = csv.reader(f, delimiter=',')
    for row in filter(None, reader):
        if cfd_number == row[0]:
            cfd_checked_before = "Yes"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM