所以我试着写一段代码,从一个文件中提取文本,移动到一个字典中,然后处理它。我经常会遇到这样的错误:
File "C:\Users\Oghosa\Assignment2.py", line 12, in <module>
builtins.IndexError: string index out of range
以下是我的程序:
endofprogram = False
dic = {}
try:
filename = input("Please Enter the Filename:")
infile = open(filename, 'r')
except IOError:
print("Error Reading File! Program ends here!")
endofprogram = True
if endofprogram == False:
for line in infile:
line = line.strip("\n")
if (line != " ") and (line[0] != "#"):
item = line.split(":")
print(items)
dic["Animal id"] = item[0]
dic["Date"] = item[1]
dic["Station"] = item[2]
print(dic)
有人能帮忙指出我的错误吗?你知道吗
下面是一个输入文本示例:
#Comments
a01:01-24-2011:s1
a03:01-24-2011:s2
<blank line>
<blank line>
a02:01-24-2011:s2
a03:02-02-2011:s2
a03:03-02-2011:s1
a02:04-19-2011:s2
<blank line>
#comments
a01:05-14-2011:s2
a02:06-11-2011:s2
a03:07-12-2011:s1
a01:08-19-2011:s1
a03:09-19-2011:s1
a03:10-19-2011:s2
a03:11-19-2011:s1
a03:12-19-2011:s2
好吧,你至少应该把这句冒犯的话打印出来,这样你就知道罪魁祸首是什么了:
您的问题是,当文件中有空行时,
line[0]
不存在。要解决此问题,请尝试此版本:同样值得注意的是,在循环的每次迭代中都会覆盖
dic
。所以循环完成后,dic
将只包含文件最后一行的信息。你知道吗相关问题 更多 >
编程相关推荐