在Context Manager - Python期间发生捕获异常

pau*_*aul 3 python contextmanager python-3.x

可能重复:
使用带有try-except块的python"with"语句

我正在用openPython打开一个文件.我将文件处理封装在一个with语句中:

with open(path, 'r') as f:
    # do something with f
    # this part might throw an exception
Run Code Online (Sandbox Code Playgroud)

这样我就确定我的文件已关闭,即使抛出了异常.

但是,我想处理打开文件失败的情况(OSError抛出一个).一种方法是将整个with块放在一个try:.只要文件处理代码不引发OSError,这就可以工作.

它可能看起来像:

try:
   with open(path, 'rb') as f:
except:
   #error handling
       # Do something with the file
Run Code Online (Sandbox Code Playgroud)

这当然不起作用,真的很难看.这样做有一种聪明的方法吗?

谢谢

PS:我正在使用python 3.3

Mar*_*ers 12

首先打开文件,然后将其用作上下文管理器:

try:
   f = open(path, 'rb')
except IOError:
   # Handle exception

with f:
    # other code, `f` will be closed at the end.
Run Code Online (Sandbox Code Playgroud)