我想用文本文件中的新值替換一些值。我有一個包含舊值的列表(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