【问题标题】:Need help scanning through lines lines of a .csv file需要帮助扫描 .csv 文件的行
【发布时间】:2017-11-19 18:22:38
【问题描述】:

我需要扫描 .csv 文件中的每一行,但一旦我扫描到最后,就会出现错误。

def percentage():
    for line in csv_file:
        temp = line.strip("\n")

        measureType = temp.split(",")[5][1: -1]

        if measureType == "PERCENT":
            year = line.split(",")[1][1: -1]
            percentage = line.split(",")[6][1: -2]
            country = line.split(",")[0][1: -1]

            if float(percentage) < 50:
                output.addCountry(country, year, percentage)

当我扫描文件时,一旦它到达末尾,它就会给我一个错误:

IndexError: list index out of range

对于下面的行:

measureType = temp.split(",")[5][1: -1]

我非常困惑,不知道我必须解决什么问题。

【问题讨论】:

  • 文件的最后一行是什么?
  • 听起来这个文件最后有一个空行。

标签: python python-2.7 file csv


【解决方案1】:

离开 cosinepenguin 所说的内容,您将不得不查看最后一行。

出现错误的原因是因为您试图用每个逗号分隔行,然后尝试获取不存在的索引。

例子:

array = [0, 1, 2]

在这个数组中有3个索引,所以如果你尝试获取比最后一个更高的索引,你会得到错误IndexError: list index out of range


所以要确保最后一行,在被分割之后,有你需要的所有索引。

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2018-07-28
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 2021-02-23
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多