![](/img/trans.png)
[英]Why am I getting IndexError: list index out of range for this function?
[英]Why am I getting IndexError: list index out of range error even though I have a proper list
with open('Input','r') as f:
while len(a)>0:
a=f.readline() #I am going to search for a command to execute in the txt file
w_in_line=a.split(',') #words in line
command_word_box=w_in_line[0].split()#I took the command word out of the line
command_word=str(command_word_box[0])
pat_name=w_in_line[0].replace(command_word,'')
w_in_line[0]=pat_name
for word in command_word_box: #searching for commands
if word=='create':
create (w_in_line)
else:
continue
文本文件是:
a
create Hayriye, 0.999, Breast Cancer, 50/100000, Surgery, 0.40
remove Hayriye
我正在嘗試讀取文本文件並找到一個命令並為每一行執行命令因此我在逗號之前分隔了第一部分並將其放入command_word_box
,然后我從中取出第一個詞來檢測我的命令並將其存儲在command_word
但我不斷得到
command_word=str(command_word_box[0])
IndexError: list index out of range
如 output。
我可以成功打印command_word_box
和command_word
,它按照我的預期以列表格式提供正確的輸出, command_word_box
中有 2 個元素,但顯然由於某種原因它沒有將command_word_box[0]
作為有效索引。
當您讀取文件的最后(空白)行時會出現問題。 您在閱讀下一行之前檢查條件len(a)
,這太早了。 解決方案:
a=f.readline()
while len(a) > 0:
w_in_line=a.split(',') #words in line
# The rest of your loop here
a=f.readline()
更好的方法是使用for
循環:
for a in f:
w_in_line=a.split(',') #words in line
# The rest of your loop here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.