1

我想用来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

两个问题:

  1. 我是否正确实施了这一点?
  2. 我可以对此进行测试以确保文件被关闭还是我只是相信它?

我使用打印语句来表示何时__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
>>>
4

1 回答 1

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.

而当函数退出时,如果出现异常,会正常处理。

于 2014-07-12T04:49:26.173 回答