2

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

  • 1
    Relevant http://stackoverflow.com/questions/5071121/raii-in-python-automatic-destruction-when-leaving-a-scope – shadyabhi Jan 28 '12 at 01:14
  • 1
    I can't fathom what "the number of files is not known before-hand" can possibly mean. Can you provide an explanation for this algorithm which opens (and keeps open) an unknown number of files. – S.Lott Jan 28 '12 at 03:27
  • 1
    Example: a script that takes a variable number of filenames on the command-line and interleaves them all line-by-line to stdout . – user1174648 Jan 28 '12 at 08:36

2 Answers2

4

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.

Amber
  • 507,862
  • 82
  • 626
  • 550
0

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.

Kevin
  • 28,963
  • 9
  • 62
  • 81