我想使用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__
时使用print语句来表示信号是否足够?
>>> 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
>>>
答案 0 :(得分:1)
看起来很好,是的,你可以相信它,但我会明确地将参数命名为__exit__
:
def __exit__(self, exc_type, exc_value, traceback):
print 'closing files'
for arg in (exc_type, exc_value, traceback):
print arg,
for f in self.files:
f.close()
return False # does not suppress the exception.
当函数退出时,如果有异常,它将被正常处理。