列表索引错误(超出范围)在python中没有意义

时间:2021-10-24 16:39:01

So I am trying to separate a text file using line.split() and a for loop, but I am getting an index error. I have read around and understand why this error is given but I don't understand how index[0] and index[1] could be out of range (I bolded the line that is returning the error):

所以我试图使用line.split()和for循环来分隔文本文件,但是我收到索引错误。我已阅读并理解为什么会出现此错误,但我不明白index [0]和index [1]如何超出范围(我用粗体表示返回错误的行):

names = {} file = open('sourcefile.txt', 'r') text += file.readlines() file.close() for line in text: tmp = line.split() **names[tmp[1]] = tmp[0]**

names = {} file = open('sourcefile.txt','r')text + = file.readlines()file.close()for line in text:tmp = line.split()** names [tmp [1 ]] = tmp [0] **

sourcefile.txt looks like this: 1 (data and numbers) 2 (data and numbers) 3 (data and numbers) 4 (data and numbers)

sourcefile.txt如下所示:1(数据和数字)2(数据和数字)3(数据和数字)4(数据和数字)

If anyone can help I would appreciate it a lot.

如果有人可以提供帮助,我会非常感激。

Edit forgot to mention I am using python in the title

编辑忘了提到我在标题中使用python

1 个解决方案

#1


I suspect that there's a problem reading the file and file.readLines() is returning an empty set, making text an empty string. It would follow that the split() results in an array of length 0, making even index=0 out or range.

我怀疑读取文件时出现问题,file.readLines()返回一个空集,使文本为空字符串。接下来,split()会产生一个长度为0的数组,使得甚至index = 0 out或range。

#1


I suspect that there's a problem reading the file and file.readLines() is returning an empty set, making text an empty string. It would follow that the split() results in an array of length 0, making even index=0 out or range.

我怀疑读取文件时出现问题,file.readLines()返回一个空集,使文本为空字符串。接下来,split()会产生一个长度为0的数组,使得甚至index = 0 out或range。