我想用来itertools.izip()
迭代多个文件的行。我创建了一个上下文管理器类型,以确保所有文件在与with
. 这似乎有效:
class Files_Iterator(object):
"""Sequential line iteration from multiple files
"""
def __init__(self, files):
"""files --> list or tuple of str, file paths
"""
self.files = files
def __enter__(self):
print 'opening files'
self.files = map(open, self.files)
return it.izip(*self.files)
def __exit__(self, *exception_args):
print 'closing files'
for arg in exception_args:
print arg,
for thing in self.files:
thing.close()
return False
两个问题:
- 我是否正确实施了这一点?
- 我可以对此进行测试以确保文件被关闭还是我只是相信它?
我使用打印语句来表示何时__exit__
被调用 - 这是一个足够的测试吗?
>>> with Files_Iterator(['file1.txt', 'file2.txt']) as files:
for lines in files:
print lines
raise Exception
opening files
('File1Line1\n', 'File2Line1\n')
closing files
<type 'exceptions.Exception'> <traceback object at 0x0313DFD0>
Traceback (most recent call last):
File "<pyshell#48>", line 4, in <module>
raise Exception
Exception
>>>