问题描述
考虑以下几点:
with open(path, mode) as f:
return [line for line in f if condition]
文件会正确关闭,还是使用 return 以某种方式绕过 上下文管理器一个>?
Will the file be closed properly, or does using return somehow bypass the context manager?
推荐答案
是的,它就像 try 块之后的 finally 块,即它总是执行(除非当然,python 进程以一种不寻常的方式终止).
Yes, it acts like the finally block after a try block, i.e. it always executes (unless the python process terminates in an unusual way of course).
PEP-343 的一个例子中也提到过这是 with 语句的规范:
It is also mentioned in one of the examples of PEP-343 which is the specification for the with statement:
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).
但值得一提的是,如果不将整个 with 块放入 try..除了块,这通常不是人们想要的.
Something worth mentioning is however, that you cannot easily catch exceptions thrown by the open() call without putting the whole with block inside a try..except block which is usually not what one wants.
这篇关于在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)