我想用文本文件中的新值替换一些值。我有一个包含旧值的列表(c)和一个包含新值的列表(iteml)。 我的代码是:为什么我得到“IndexError:列表索引超出范围”错误?
def write_file(self):
iteml=[]
for row in range(152):
item=self.model.item(row,1)
item.text()
text=str(item.text())
iteml.append(text)
alt=open("file","r")
neu=open("newfile","w")
x=0
for line in alt:
if line[0] == "|":
neu.write(line)
if line[0] != "|":
line=line.replace(c[x],iteml[x])
x=x+1
neu.write(line)
C []被定义全球性的,是152个元件长,所以我不知道为什么在 “行= line.replace(C [X],iteml [X])”出现索引错误。
当我使用“print(c)”或“print(iteml)”时,我得到整个列表......我的失败在哪里?
你为什么不打印X上的错误前行,看到它的价值是什么...即时猜测它比数组大小... –
读取文件中的行数大于152,不是吗? – Deck
是的,你是对的。如果我在错误发生之前打印x,x计数到152.读取的文件有超过152行。 – Hubschr