Skip to main content
 首页 » 编程设计

python之迭代多个生成器(文件句柄)

2025年05月04日16yxwkf

一次从多个文件中读取一行的最佳方法是什么(遍历多个生成器)。

我的尝试:

files = ['a.dat', 'b.dat', 'c.dat'] 
fHandles = [open(file, 'r') for file in files] 
for line in zip(*fHandles): 
    print line[0] 
    print line[1] 
    print line[2] 

有更好的方法吗?

(感觉zip(*fHandles)有点搞笑...)

请您参考如下方法:

zip 会急切地读取所有文件的全部内容,因此内存效率不高。鉴于每个文件的行数也可能不同,如果您想同时遍历这些行,我建议您使用 itertools.izip_longest。

import itertools 
 
files = ['a.dat', 'b.dat', 'c.dat'] 
handles = [open(file, 'r') for file in files] 
 
for a, b, c in itertools.izip_longest(*handles, fillvalue=''): 
    print a 
    print b 
    print c 

此外,不要忘记在完成文件后关闭它们。

for handle in handles: 
    handle.close()