【问题标题】:IndexError: list index out of range - CSV fileIndexError:列表索引超出范围 - CSV 文件
【发布时间】:2014-04-10 14:45:21
【问题描述】:

我的代码有错误 - 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]

这是因为我的文件由于编辑而有空行,解决这个问题的最简单方法是让它跳过这些行,我该怎么做?

【问题讨论】:

  • 您是否尝试过打印row?看起来它可以提供一些见解。
  • 类似于上面的 cmets。您的其中一行的条目少于 2 个。您可以使用 if len(row) > 1: 跳过此类行,但最好先了解失败情况
  • 请注意,如果您使用的是 Python 3,则应使用'r', newline=''),而不仅仅是'r',如the docs 中所述。
  • 该文件确实有一行,其中没有任何内容,并且由于编辑而将保持这种状态,因此在这里允许这样做会容易得多,该怎么做?

标签: python csv python-3.x


【解决方案1】:

for 循环中的一个简单条件可以解决问题。

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多