为什么这段代码抛出一个IndexError?

时间:2016-05-20 15:53:38

标签: python indexing

我正在尝试使用此代码从文件data.txt中读取值。但是,它在运行时会抛出一个IndexError。为什么会发生这种情况?

def main():

    myfile=open('data.txt','r')
    line=myfile.readline()
    while line!='':
        line=line.split()
        age=line[1]


        line=myfile.readline()
    myfile.close()    
main()

3 个答案:

答案 0 :(得分:2)

如果line恰好包含一个片段,line.split()会返回一个恰好一个元素的列表,并且访问其第二个元素(在索引1处)会导致错误。

此外,为了使您的代码更好,请不要重新分配变量。它阻碍了读者,代码主要是为了阅读,特别是你自己。

我使用更简单的循环:

for line in myfile:  # this iterates over the lines of the file
  fragments = line.split()
  if len(fragments) >= 2:
    age = fragments[1]
    ...

此外,在特定时间内打开文件并自动关闭文件的惯用方法是使用with

with open(...) as myfile:
  for line in myfile:
     ...
# At this point, the file will be automatically closed.

答案 1 :(得分:0)

def main():
    myfile=open('data.txt','r')
    line=myfile.readline()
    while line!='':
        line=line.split()
        try:
            age=line[1]
        except IndexError:
            age = None
        line=myfile.readline()
    myfile.close()    
main()

try语句的工作原理如下。

首先,执行try子句(try和except关键字之间的语句)。 如果没有发生异常,则跳过except子句并完成try语句的执行。 如果在执行try子句期间发生异常,则跳过该子句的其余部分。然后,如果其类型匹配except关键字后面的异常,则执行except子句,然后在try语句之后继续执行。 如果发生的异常与except子句中指定的异常不匹配,则将其传递给外部try语句;如果没有找到处理程序,则它是一个未处理的异常,执行将停止并显示一条消息。

有关详细信息,请参阅https://docs.python.org/2/tutorial/errors.html#handling-exceptions

答案 2 :(得分:0)

Python开始索引为0。 在你的age=line[1]部分中,如果该行中只有一个单词,Python会抛出一个IndexError来告诉你。查看您的数据会有所帮助,但以下是普遍接受且更容易阅读文件的方法:

with open('data.txt', 'r') as myfile:
    for line in myfile:
        # '' is a a false value, so, this is the same as if line != ''
        if line:
            line = line.split()
            # if age is always the first thing on the line:
            age = line[0]
            # if age can be somewhere else on the line, you need to do something more complicated

请注意,由于您使用了with,因此您不需要自己关闭文件,with语句就是这样做

相关问题