索引器:列表索引超出范围-python

索引器:列表索引超出范围-python,python,csv,python-3.x,opencsv,Python,Csv,Python 3.x,Opencsv,我有以下错误: currency = row[0] IndexError: list index out of range 代码如下: crntAmnt = int(input("Please enter the amount of money to convert: ")) print(currencies) exRtFile = open ('exchangeRate.csv','r') exchReader = csv.reader(exRtFile)

我有以下错误:

currency = row[0]
IndexError: list index out of range
代码如下:

 crntAmnt = int(input("Please enter the amount of money to convert: "))
    print(currencies)
    exRtFile = open ('exchangeRate.csv','r')
    exchReader = csv.reader(exRtFile)
    crntCurrency = input("Please enter the current currency: ")
    validateloop=0
    while validateloop == 0:
        for row in exchReader:
                currency = row[0]
                if currency == crntCurrency:
                    crntRt = row[1]
                    validateloop=+1
以下是CSV文件:

日元,169.948

美元,1.67

英镑,1英镑

欧元,5.5

下面是一个输入/输出示例:

Please enter the amount of money to convert: 100
['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
Please enter the current currency: Pound Sterling

试着打印出这一行。python中变量名的约定是像这样的
,而不是像这样的
。您可能会发现
break
关键字很有用:

for row in exch_reader:
    currency = row[0]
    if currency == crnt_currency:
        crnt_rt = row[1]
        break
要仅在行实际包含某些内容时为该行编制索引,请执行以下操作:

currency = row and row[0]

此处,只有当
的计算结果为
时,才会执行
行[0]
,这可能是因为它至少有一个元素。

您的csv文件中可能有一个空行,导致它生成一个空列表

有两种解决方案


一,。检查是否存在元素,仅当存在以下元素时才继续:

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


二,。短路
操作员,使
货币
成为空列表,该列表与
crntCurrency
不匹配:

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


我经常发现谦逊的
印刷版
声明最有效。。。例如,您可以使用它来查看
行中的内容
。正如@kindall所说,您可以放置一些打印语句并向我们展示它们的输出吗?或者,您可以向我们展示
exchangeRate.csv
中的内容……我不知道这有什么用处?。。。你看不出知道
是否有第0个元素,或者实际上是一个列表是多么有用?