【问题标题】:I have run into an IndexError: list index out of range, when the line is longer than the index selected当行长于所选索引时,我遇到了 IndexError: list index out of range
【发布时间】:2020-11-15 23:10:28
【问题描述】:

我希望遍历文件到每一行上的选定索引,但即使行上的变量比我选择的索引多,我也会收到此错误。

for thing in lines:
    item = thing.split(',')
    **price = item[4]**
    total_Stock_Value = total_Stock_Value + float(price)
print('Total Value of Books in Stock: £{:0,.2f}'.format(total_Stock_Value,'\n'))

【问题讨论】:

  • 你为什么要thing.split('\n'),你不需要用“\n”分割行
  • 我们可以看看您正在摄取/崩溃的行的示例吗?任何数量的事情都可能发生在这里。谢谢
  • 您能否从您的数据文件中提供一些样本来重现该问题?
  • P.G. Wodehouse, Right Ho Jeeves, hb, Penguin, 10.99, 5, 小说,
  • 您可以尝试这样的方法来识别麻烦的行:tryprice = item[4]except IndexError:print("Problem with line:", item)

标签: python


【解决方案1】:

检查文件末尾是否有空换行符,这是发生这种情况的常见位置。发生错误是有原因的,所以一定有一行没有足够的逗号。

【讨论】:

  • 好主意。大概就是这个了。只要有 any 行没有足够的逗号,错误就会在循环中的某个时间发生。
  • 知道了,文件中有一个空行。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
  • 1970-01-01
相关资源
最近更新 更多