pythonwith-statementcontextmanager

Open a list of files using with/as context manager


Note: I am aware of the

with open('f1') as f1, open('f2') as f2:
    ...

syntax. This is a different question.


Given a list of strings file_names is there a way using with/as to open every file name in that using a single line. Something such as:

with [open(fn) for fn in file_names] as files:
    # use the list of files

which of course doesn't work as it attempts to use the context manager on a list. The length of the list is not known until runtime


Solution

  • If you have access to Python 3.3+, there is a special class designed exactly for this purpose: the ExitStack. It works just like you'd expect:

    with contextlib.ExitStack() as stack:
        files = [stack.enter_context(open(fname)) for fname in filenames]
        # All opened files will automatically be closed at the end of
        # the with statement, even if attempts to open files later
        # in the list raise an exception