gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:50 24 4
gpt4 key购买 nike

我想使用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. 我可以对此进行测试以确保文件已关闭还是我只是信任它?

我使用 print 语句在调用 __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
>>>

最佳答案

看起来不错,是的,你可以相信它,但我会明确将参数命名为 __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.

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

关于python - 迭代多个文件的上下文管理器类型 - 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24709742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com