使用 "with open" 在 Python 中打开 reading/writing 的多个文件,而不单独枚举和列出每个文件?

Opening multiple files for reading/writing in Python using "with open", without enumerating and listing each one exclusively?

知道怎么做:

with open("file1.txt","w") as file1, open("file2.txt","w") as file2, open("file3.txt","w") as file3, open("file4.txt","w") as file4:

想要大致做的事情:

with open([list of filenames],"w") as [list of file variable names]:

有什么办法吗?

您可以使用 contextlib.ExitStack 作为文件处理程序的容器。它会自动关闭所有打开的文件。

示例:

filenames = "file1.txt", "file2.txt", "file3.txt", "file4.txt"
with ExitStack() as fs:
    file1, file2, file3, file4 = (fs.enter_context(open(fn, "w")) for fn in filenames)
    ...
    file2.write("Some text")