Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 迭代多个文件的上下文管理器类型-测试_Python_Contextmanager - Fatal编程技术网

Python 迭代多个文件的上下文管理器类型-测试

Python 迭代多个文件的上下文管理器类型-测试,python,contextmanager,Python,Contextmanager,我想使用itertools.izip()迭代多个文件的行。我创建了一个上下文管理器类型,以确保在使用和时关闭所有文件。 这似乎有效: class Files_Iterator(object): """Sequential line iteration from multiple files """ def __init__(self, files): """files --> list or tuple of str, file paths

我想使用
itertools.izip()
迭代多个文件的行。我创建了一个上下文管理器类型,以确保在使用
时关闭所有文件。 这似乎有效:

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
两个问题:

  • 我是否正确地实现了这一点
  • 我可以测试这个以确保文件被关闭,还是我只是信任它
  • 我使用print语句在调用
    \uuuuu exit\uuuu
    时发出信号-这是一个足够的测试吗

    >>> 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
    >>>
    
    >>将文件作为迭代器(['file1.txt','file2.txt'])作为文件:
    对于文件中的行:
    打印行
    引发异常
    打开文件
    ('File1Line1\n','File2Line1\n')
    关闭文件
    回溯(最近一次呼叫最后一次):
    文件“”,第4行,在
    引发异常
    例外情况
    >>>
    
    看起来不错,是的,您可以信任它,但我会明确地将参数命名为
    \uuuuu exit\uuuu

    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.
    

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

    您可能知道这将同时打开所有文件。如果您确定文件只按顺序使用,则返回自定义迭代器可以确保一次只打开一个文件,并且外部带有的
    可以处理最后一个(单个)文件的清理。FWIW,使用
    contextlib.contextmanager
    便利类编写此命令会更好。@Veedrac,其目的是从每个文件生成行,因此-我实际上没有考虑(做出决定)是否所有文件都应该同时保持打开状态。我看了
    contextlib.contextmanager
    -我不知道为什么我没有走这条路。@Veedrac,你是对的,修饰函数更容易阅读(至少对我来说)。我在这里用过,