Created
January 8, 2012 16:47
-
-
Save dcrosta/1578946 to your computer and use it in GitHub Desktop.
multiple-file context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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