When I process one file, I can use with statement to ensure it is always closed, on success or failure. Such as
with open('some_file', 'r') as f:
print f.read()
However, I now need to open a list of files, the number of which is only known at runtime, so I cannot use nested with statements. But can I use it with a list? Kind of like
with [open(fn) for fn in file_names] as files:
#do something
The above obviously doesn't work. What will work?
As @Marcin mentioned in the comments, I don't believe there is a way to do this using a list and
with.However,
withis essentially syntactic sugar for a set oftry/except/finallyblocks that allows for encapsulation and therefore easier reuse.While you can specify multiple pairings within a single
with, i.e.There's not an allowance for dynamic variables there such as
lists ortuples. This form is actually treated as if the comma-separated expressions are nestedwiths.However, what you could do instead is essentially ignore the syntactic sugar of
withand rely on the original syntax it was meant to replace. That is, encapsulate your logic within a set oftry/except/finallyblocks. That way, you can open a list of files at runtime, and then ensure via thefinallyclause that they get cleaned up.Something of the form: