Skip to content

Instantly share code, notes, and snippets.

@dcrosta
Created January 8, 2012 16:47
Show Gist options
  • Save dcrosta/1578946 to your computer and use it in GitHub Desktop.
Save dcrosta/1578946 to your computer and use it in GitHub Desktop.
multiple-file context manager
class openFiles(object):
def __init__(self, *args):
if not all(isinstance(arg, tuple) for arg in args):
raise TypeError('arguments to openFiles must all be 2-tuples')
if not all(len(arg) in (1, 2) for arg in args):
raise TypeError('arguments to openFiles must all be 2-tuples')
self.args = args
def __enter__(self):
self.fhs = [file(*arg) for arg in self.args]
return self.fhs
def __exit__(self, type, value, traceback):
for f in self.fhs:
f.close()
with openFiles(('test.txt', 'r'), ('test2.txt', 'r')) as ll:
print ll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment