What is the "best" way to open a variable number of files in python?
I can't fathom how to use "with" if the number of files is not known before-hand.
(Incoming from RAII/C++)
What is the "best" way to open a variable number of files in python?
I can't fathom how to use "with" if the number of files is not known before-hand.
(Incoming from RAII/C++)
Well, you could define your own context manager that took a list of (filename, mode)
pairs and returned a list of open file handles (and then closed all of those handles when the contextmanager exits).
See http://docs.python.org/reference/datamodel.html#context-managers and http://docs.python.org/library/contextlib.html for more details on how to define your own context managers.
With 3.3, contextlib.ExitStack
is now available for situations such as this. Here's some example code from the contextlib
documentation:
with 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
2.7 users are out of luck. Yet another reason to upgrade.