Open file list with with statement
I am trying to open multiple files from inputs sys.argv
using instruction with
.
I know I can do this by manually typing each one:
with open(sys.argv[1], 'r') as test1, open(sys.argv[2], 'r') as test2, \
open(sys.argv[3], 'r') as test3, open(sys.argv[4], 'r') as test4:
do_something()
But is there a way to do it without doing it, for example the following pseudocode:
with open(sys.argv[1:4], 'r') as test1, test2, test3:
do_something()
source to share
You can do this in Python 3.3+ withcontextlib.ExitStack
:
from contextlib import ExitStack
with ExitStack() as stack:
files = [stack.enter_context(open(arg, 'r')) for arg in sys.arv[1:4]]
Funny, the example in the documentation is exactly what you want.
This properly closes any open files on exiting the statement with
- even if something went wrong before they were opened.
For an earlier version of python, there is a reverse path in the packagecontextlib2
that you can walk throughpip
source to share