python - 在 Python 中使用 with 运算符关闭文件

标签 python python-2.7 python-3.x

我有一个关于在 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/

相关文章:

python - Python中非线性方程的数值解

python - ChromeDriver版本不匹配错误: session not created: This version of ChromeDriver only supports Chrome version 91

python - Keras model.summary() 对象到字符串

python - 如何在 Heroku 云上部署 Scrapy 蜘蛛

python - 可变轴上的 numpy 索引

python - 尝试做一个程序来替换给定的行,由同一行但全部大写

python - 按顺序依次读取文件

python - Struct.error : argument for 's' must be a bytes object, 已经提供

python - 类型错误:不支持的操作数类型 -: 'list' 和 'list'

python - 分数背包算法 Python 输入问题