小编典典

在Python中,如果我在“ with”块内返回文件,该文件是否还会关闭?

python

考虑以下:

with open(path, mode) as f:
    return [line for line in f if condition]

文件将被正确关闭,还是使用return某种方式绕过上下文管理器


阅读 137

收藏
2020-12-20

共1个答案

小编典典

是的,它的作用就像一个finally块接一个try块,也就是说,它总是执行(除非python进程以异常的方式终止)。

PEP-343的一个示例中也提到了该with语句,它是该语句的规范:

with locked(myLock):
    # Code here executes with myLock held.  The lock is
    # guaranteed to be released when the block is left (even
    # if via return or by an uncaught exception).

但是,值得一提的是,如果open()不将整个with块放入try..except通常不是您想要的块中,就无法轻松捕获调用引发的异常。

2020-12-20