简体   繁体   中英

IndexError: list index out of range - CSV file

There is an error in my code - IndexError: list index out of range, at rates[row[0]] = row[1] :

def change():
    # read file into dictionary
    with open('exchangeRate.csv', 'r') as in_file:
        echRdr = csv.reader(in_file)
        for row in echRdr:
            rates[row[0]] = row[1]

it is because there are empty lines in my file due to editing and the easiest way to solve this is to make it skip these lines, how would i do that?

A simple condition in the for loop may solve the issue.

def change():
    # read file into dictionary
    with open('exchangeRate.csv', 'r') as in_file:
    echRdr = csv.reader(in_file)
    for row in echRdr:
        if len(row) <= 1:
            pass
        else:
            rates[row[0]] = row[1]

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