在"try"操作符内嵌套"for"循环

1 投票
6 回答
14765 浏览
提问于 2025-04-17 10:11

大家好,

我已经决定绕过这个问题,但我想确认一下Python的表现是否正常。

在这个例子中,“sample.txt”是一个可以读取和解析的多行文本文件。

try:
    file=open('sample.txt','r')
    for line in file:
          (some action here)
except:
    print "Couldn't open file"
file.close()

我观察到的情况是,“sample.txt”被打开后,第一行被处理,然后程序就跳到了“except”部分。

这是正常现象还是一个错误呢?

6 个回答

3

这个简单的 except 会捕捉到所有的错误,包括在 (some action here) 这部分可能出现的错误。可以把它改成这样:

try:
    inputfile = open('sample.txt', 'r')
except:
    print "Couldn't open file"
else:
    for line in inputfile: pass
    inputfile.close()

或者更好的是:

with open('sample.txt', 'r') as inputfile:
    for line in inputfile: pass

一般来说,尽量把 try 代码块里的内容控制在最少的范围内,这样你就不会意外地处理那些你其实没有准备好应对的错误。

3

那么问题并不是出在open这一行上,那到底是什么异常呢?

try:
    file=open('sample.txt','r')
    for line in file:
          (some action here)
except:
    print "Exception:"
    import traceback; traceback.print_exc()

file.close()
6

如果except块里的代码被执行,那说明发生了一个错误(异常)。你把这个错误给“吞掉”了,这样就很难知道到底出了什么问题。

你的错误信息显示你在尝试捕捉打开文件时出现的错误。但是因为你的try块包裹了整个文件处理的过程,所以在处理过程中出现的错误会被错误地报告为“无法打开文件”。如果你真的需要处理这个错误,那就得把for循环放到except块之后。

我个人倾向于直接忽略这个错误,让默认的错误处理机制来停止程序的执行:

with open('sample.txt','r') as file:
    for line in file:
        (some action here)

如果你必须处理这个错误,那就要仔细选择你要处理的错误类型。例如,只处理IOError,因为这是open在失败时会抛出的错误。

try:   
    with open('sample.txt','r') as file:
        for line in file:
            (some action here)
except IOError:
    except IOError as (errno, strerror):
        print "I/O error({0}): {1}".format(errno, strerror)

撰写回答