我有一个关于在 python 中使用 和
运算符关闭文件的问题
import os
with os.popen('ls') as f:
print f.read()
raise IOError
print f
print f
正如您在上面的代码中看到的,我正在使用 with
运算符打开一个文件,我知道该文件在退出 with
block 后会自动关闭,但是如果 block 内部发生错误,文件对象 f
会发生什么,它会关闭吗?
最佳答案
是的。来自 python 文档:
A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.
通常,上下文管理器将实现 try..except..finally
模式以方便和可重用。
因此,您的问题的答案是肯定的,它会处理异常。
关于python - 在 Python 中使用 with 运算符关闭文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45407695/