打开文件并在一行中对该文件执行操作是否会关闭文件?

Does opening a file and performing an operation on that file in one line close the file?

在同一行中打开文件并随后对该文件执行操作是否安全,之后不关闭文件?

例如,如果我正在使用 zipfile 模块并想要获取名为 file_list 的 zip 文件中的文件列表,执行以下操作是否安全:

import zipfile
import os
zip_path = os.path(...)

file_list = zipfile.ZipFile(zip_path).namelist()

当然,我知道这段代码可以安全地完成同样的事情,尽管只有两行:

import zipfile
import os
zip_path = os.path(...)

with zipfile.ZipFile(zip_path) as my_zip:
    file_list = my_zip.namelist()

哪个更好?

来自docs

ZipFile.close()

Close the archive file. You must call close() before exiting your program or essential records will not be written.

一般来说,使用上下文管理器几乎总是更好。它被认为更整洁、更安全。

It will close the file when it's garbage collected

# ZipFile in zipfile.py
def __del__(self):
    """Call the "close()" method in case the user forgot."""
    self.close()

如果你使用那个衬里,它不会创建一个引用,所以它应该被处理掉,然后关闭。但是你依赖于 GC 何时运行的实现细节,这不是最好的主意,你最好使用 with.

例如one liner wouldn't behave the same way with pypy