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

标签 python file generator

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

我的尝试:

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()

关于python - 迭代多个生成器(文件句柄),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28513394/

相关文章:

Python:没有变量的类实例化的意义是什么

python - Python 中用于 SQLite 的 Connection.iterdump 的替代方案?

python - 如何使用 python 中的正则表达式检查两个查询字符串(带通配符)是否存在

c# - 如何解析以下文本文件?

c - 如何使用 C 仅从包含数字和字母的数组中读取数字?

java - 输入和输出流的 IOUtils.copy() 速度非常慢

python - 从生成器创建迭代器返回相同的对象

javascript - 生成函数或异步生成函数后清理

python - 即使使用 inplace=True,pandas replace 也不会替换值

python - 当我需要数据时返回生成器对象