【问题标题】:Index Error: list index out of range (Python), numbering correct索引错误:列表索引超出范围(Python),编号正确
【发布时间】:2017-07-04 18:13:53
【问题描述】:

我知道这个问题之前已经被问过多次,但是我已经仔细检查了编号并且错误仍然出现。我想知道我是否遗漏了其他明显的东西。

with open('imagefile.csv', newline='') as csvfile:
    imagelog = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in imagelog:
        if row[0] == 'IMG' and row[2].endswith('.RAW'):
            gpsAndAtt.append({ 'label': 'IMG', 'timeMS': float(row[1]), 'file': row[2]})

错误出现在上述代码的第 4 行。但是 .csv 文件如下,3 列。或者根据Python,0,1,2

IMG,330985,033.RAW
IMG,332985,034.JPG
IMG,343985,035.RAW

该代码旨在去除 .csv 的元素,以便与另一个文件一起使用。

提前致谢。

编辑

原始问题中的空行排序问题(堆栈格式不佳)

【问题讨论】:

  • 您能否在for 循环中调用脚本后立即打印row?然后你可以确切地看到row的样子。
  • 我认为您的 csv 文件中可能有一些空行。
  • @JackParkinson 打印行返回 ['{\\rtf1\\ansi\\ansicpg1252\\cocoartf1504\\cocoasubrtf830'] ['{\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica; }'] ['{\\colortbl;\\red255\\green255\\blue255;}'] ['{\*\\expandedcolortbl;;}'] ['\\paperw11900\\paperh16840\\margl1440\\margr1440 \\vieww10800\\viewh8400\\viewkind0'] ['\\pard\\tx566\\tx1133\\tx1700\\tx2267\\tx2834\\tx3401\\tx3968\\tx4535\\tx5102\\tx5669\\tx6236\ \tx6803\\pardirnatural\\partightenfactor0'] []
  • @JackParkinson 然后是:回溯(最近一次通话最后一次):文件“/Users/Walker/Desktop/Important/SArONG Glitter Project/Code/Python/NetCDF/TextWranglerRunTemp-GetAttributesFromDroneLog.py”,第 32 行,在 中 if row[0] == 'IMG' and row[2].endswith('.RAW'): IndexError: list index out of range
  • 这些列表都没有逗号,所以看起来它们最多只有一个元素,而不是三个。而且我在任何地方都看不到“IMG,330985,033.RAW”。你确定你从正确的文件中读取?

标签: python index-error


【解决方案1】:

不是“答案”,因为从表面上看,应该没有错误,但是如果你有潜在的错误输入,你应该有一个“守卫”在您返回的“行”上,因为您正在访问行 [2]。 (出于诊断目的,无论如何都要标记/显示有问题的行!)

因此:

for row in imagelog:
  if len(row) >= 2:
      ...

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2014-11-03
    • 1970-01-01
    相关资源
    最近更新 更多