0
我得到IndexError:字符串索引超出範圍。文件「document_words」中的每一行以「-99」結尾。所以我認爲錯誤可能是因爲「-99」沒有轉換爲int。但我不確定。如果是這種情況,我該如何將「-99」轉換爲int並從循環中斷開。python IndexError:字符串索引超出範圍
以下是我的代碼:
words=open('words','r')
image=open('document_words','r')
data=open('input','a')
linecount=0
for line in image:
if line.strip():
linecount+=1
image.read()
image.seek(0,0)
while linecount>0:
line1=image.readline().split()
for entry in line1:
num=int(entry)
if (num<0):
print("break from loop")
break
else:
tag=words.readline()[num]
data.write(str(tag)+' ')
data.write('\n')
linecount=linecount-1
data.flush()
data.close()
words.close()
image.close()
錯誤狀態是什麼行? – TerryA
錯誤將出現在此行tag = words.readline()[num]。 '文字'文件將是空的。此外,您已經以只讀模式打開「文字」文件並嘗試寫入文件。 – rajpy
@Haidro:我用打印語句,直到-99讀取圖像的第一行。然後給出: 文件「get.py」,第26行,在 tag = words.readline()[num] IndexError:字符串索引超出範圍 –
nish