python with block self-closures 打开的资源?

Is python with block self closing opened resource?

我是一个经验丰富的 Java 开发人员,我想知道 python 中的 with 块是否与 Java 嵌入的 try/catch 一样。在以下示例中,我将写入 python 和 Java

中的随机文件
import io

with io.open("filename", "w") as file:
   file.write("a test")
   #is file.close() necessary here ?
   #file.close()


File file = new File("test.txt");
try(FileWriter writer = new FileWriter(file)) {
    writer.write("a test");
    // here writer.close() is useless as it is auto closed by the try catch block
} catch(IOException e){
    e.printStackTrace();
}

这 2 个块的行为完全相同,还是 python 块直到程序结束才关闭资源?

是的,在这种特殊情况下,with 的行为类似于 Java 的 try-with-resource 结构。当 with 块退出时文件关闭。

with 块的目的更通用。有关使用上下文管理器的说明,请参阅 herewith 块的确切行为取决于 __enter__,更常见的是 __exit__ 对象的方法被赋予 with 块。在这种情况下,open returns 一个 TextIOWrapper 对象(或类似的 class;它可以变化),并且 TextIOWrapper 定义了一个 __exit__ 方法调用时自动关闭。

(open is a builtin, so you don't need to import io, io.open is simply an alias for open.)

使用您的示例就像您这样做一样:

file = open('filename', 'w')
try:
    file.write("a test")
finally:
    file.close()

所以这意味着文件会自动关闭,无论是成功还是引发异常。

关于with声明的更多信息,我推荐Python文档:

上下文管理器是非常有用且用途广泛的工具,我建议阅读更多有关它们的信息!

您只需要:

with open('filename', 'w') as file:
    file.write('a test')

您无需致电 file.closewith 块退出时文件将关闭,即使出现异常。这是使用 with.

的部分优势