文件到字典,无法让程序运行

时间:2013-11-26 02:56:19

标签: python python-3.x dictionary indexing

所以我试着编写一段代码来从文件中获取文本,移入字典然后处理它。我一直收到这个错误:

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

5 个答案:

答案 0 :(得分:0)

您的档案中是否有空行?在第12行,您可能希望在使用line[0]对其进行索引之前检查该行是否包含文本。你真的有一行第12行应该读的空字符串:

if line.strip() and (line[0] != "#"):

编辑..添加完整示例。

dic = {}
filename = input("Please Enter the Filename:")
try:
    infile = open(filename, 'r')
except IOError:
    print("Error Reading File! Program ends here!")
else:
    for line in infile:
        line = line.strip()
        if line and line[0] != "#":
            item = line.split(":")
            dic["Animal id"] = item[0]
            dic["Date"] = item[1]
            dic["Station"] = item[2]

答案 1 :(得分:0)

好吧,你至少应该打印违规行,这样才能知道罪魁祸首是什么:

for line in infile:
    items = line.strip("\n")
    try:
        if (line.strip != "") and (items[0] != "#"):
            items = line.split(":") #i dont like your reuse of line so changing to items
            ....
    except IndexError: #if python 3 use except IndexError as e:
        print(items) #prints offending line 

答案 2 :(得分:0)

    endofprogram = False
    attrs=["Animal id","Date","Station"]
    dictionary=[]
    try:
        # filename = input("Please Enter the Filename:")   
        infile = open('rite.txt', '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(":")
                dictionary.append(dict(zip(attrs, item)))
    print dictionary

答案 3 :(得分:0)

您的问题是,当文件中有空行时,line[0]不存在。要解决此问题,请尝试以下版本:

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 len(line):
            if line[0] != "#":
                item = line.split(":")
                print(items)
                dic["Animal id"] = item[0]
                dic["Date"] = item[1]
                dic["Station"] = item[2]
            print(dic)

另外值得注意的是,您在循环的每次迭代中都覆盖dic。所以循环完成后; dic仅包含文件最后一行的信息。

答案 4 :(得分:0)

问题是你没有在

中正确检查空行
    if (line != " ") and (line[0] != "#"):

语句。这是因为在line = line.strip("\n")执行后它们甚至没有留下空间,所以几乎任何索引操作都会失败。

下面的代码已修复该问题并修复了其他几个编码错误。请注意,在此处发布您的实际代码非常重要,以便人们更轻松地为您提供帮助。

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 not endofprogram:
    for line in infile:
        line = line.strip("\n")
        if line and line[0] != "#":
            items = line.split(":")
            print(items)
            dic["Animal id"] = items[0]
            dic["Date"] = items[1]
            dic["Station"] = items[2]
    print(dic)