【问题标题】:Catch exception happening during Context Manager - Python [duplicate]在上下文管理器期间捕获异常 - Python [重复]
【发布时间】:2023-03-23 10:15:02
【问题描述】:

可能重复:
Using python “with” statement with try-except block

我正在使用open 在 Python 中打开一个文件。我将文件处理封装在 with 语句中,如下所示:

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

这样我可以确定我的文件已关闭,即使引发了异常。

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

它可能看起来像:

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

这当然行不通,而且真的很丑。有没有一种聪明的方法来做到这一点?

谢谢

PS:我使用的是 python 3.3

【问题讨论】:

    标签: python python-3.x contextmanager


    【解决方案1】:

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

    try:
       f = open(path, 'rb')
    except IOError:
       # Handle exception
    
    with f:
        # other code, `f` will be closed at the end.
    

    【讨论】:

    • 谢谢。正是我需要的
    • @paul:然后接受这个答案(如果你认为值得,也可以投票)。
    • 这里 f 将超出范围。 .即无法访问'f'
    • @SandeepDas:我假设处理请求意味着您将退出函数或不继续使用f 作为上下文管理器。如果您不退出,可以在此处使用else: 块(try: 语句的一部分)。
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2015-05-29
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    相关资源
    最近更新 更多