Reputation: 177
I'm trying to open several files from sys.argv
inputs using a with
statement.
I know I can do it by manually typing out 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 this without doing so, like the following pseudocode:
with open(sys.argv[1:4], 'r') as test1, test2, test3:
do_something()
Upvotes: 3
Views: 635
Reputation: 97641
You can do this in Python 3.3+ with contextlib.ExitStack
:
from contextlib import ExitStack
with ExitStack() as stack:
files = [stack.enter_context(open(arg, 'r')) for arg in sys.arv[1:4]]
Amusingly, the example in the documentation is exactly what you want.
This correctly closes any open files upon exiting the with
statement - even if something went wrong before they were all open
For earlier version of python, there is a backport in the contextlib2
package, which you can get through pip
Upvotes: 2