[英]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.