Search code examples
pythonfileiofilewriter

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


What I know how to do:

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:

What I want to approximately do:

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

Any way to do that?


Solution

  • You can use contextlib.ExitStack as container for file handlers. It will close all opened files automatically.

    Example:

    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")