为什么这个代码会抛出索引器?

2024-04-19 05:37:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从文件中读取值,数据.txt,使用此代码。但是,当我运行它时,它抛出一个索引器。为什么会这样?你知道吗

def main():

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


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

Tags: 数据代码txtcloseagedatareadlinemain
3条回答
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

如果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.

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语句就可以完成这项工作

相关问题 更多 >