考虑以下:
with open(path, mode) as f: return [line for line in f if condition]
文件将被正确关闭,还是使用return某种方式绕过上下文管理器?
return
是的,它的作用就像一个finally块接一个try块,也就是说,它总是执行(除非python进程以异常的方式终止)。
finally
try
PEP-343的一个示例中也提到了该with语句,它是该语句的规范:
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通常不是您想要的块中,就无法轻松捕获调用引发的异常。
open()
try..except