在Python中使用 "with open "打开多个文件进行读写,而不需要专门列举和列出每个文件?[重复]

问题描述 投票:0回答:1

我的意思是 知道 如何做。

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]:

有什么方法可以做到这一点?

python file io filewriter
1个回答
1
投票

你可以使用 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")
© www.soinside.com 2019 - 2024. All rights reserved.