IndexError: list index out of range - python

岁酱吖の 提交于 2019-11-30 23:15:53

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:

Try printing out the row. The convention for variable names in python are like_this and not likeThis. You might find the break keyword useful:

for row in exch_reader:
    currency = row[0]
    if currency == crnt_currency:
        crnt_rt = row[1]
        break

To only index the row when the row actually contains something:

currency = row and row[0]

Here row[0] is only executed if row evaluates to True, which would be when it has at least one element.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!