IndexError: list index out of range - python

后端 未结 2 2040
予麋鹿
予麋鹿 2021-01-06 17:34

I have the following error:

currency = row[0]
IndexError: list index out of range

Here is the code:

 crntAmnt = int(input(         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 18:08

    You probably have a blank row in your csv file, causing it to produce an empty list

    There are a couple solutions


    1. Check if there are elements, only proceed if there are:

    for row in exchReader:
        if len(row):  # can also just do   if row:
            currency = row[0]
            if currency == crntCurrency:
    

    2. Short-circuit an and operator to make currency an empty list, which won't match crntCurrency:

    for row in exchReader:
        currency = row and row[0]
        if currency == crntCurrency:
    

提交回复
热议问题