如何在Python中捕获`with open(filename)`引发的异常?

kuzzooroo

尝试在Python中打开文件的行为可能会引发异常。如果我使用with语句打开文件,是否可以捕获open调用和相关__enter__调用引发的异常而又不捕获with块中代码引发的异常

try:
    with open("some_file.txt") as infile:
        print("Pretend I have a bunch of lines here and don't want the `except` below to apply to them")
        # ...a bunch more lines of code here...
except IOError as ioe:
    print("Error opening the file:", ioe)
    # ...do something smart here...

这个问题与这个较早的问题不同,因为这个较早的问题是关于编写上下文管理器的,而不是使用熟悉的with open

杰夫斯

是否可以捕获open调用和相关__enter__调用引发的异常,而不能捕获with块中的代码引发的异常?

是的:

#!/usr/bin/env python3
import contextlib

stack = contextlib.ExitStack()
try:
    file = stack.enter_context(open('filename'))
except OSError as e:
    print('open() or file.__enter__() failed', e)
else:
    with stack:
        print('put your with-block here')

使用默认open()功能时,__enter__()不应引发任何有趣的异常,因此可以简化代码:

#!/usr/bin/env python    
try:
    file = open('filename')
except OSError as e:
    print('open() failed', e)
else:
    with file:
        print('put your with-block here')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章