【问题标题】:Python Read Large Text FilesPython 读取大文本文件
【发布时间】:2017-09-23 17:34:53
【问题描述】:

我试图逐行比较两个大文本文件(每个 10GB)而不将整个文件加载到内存中。我使用了其他threads中所示的以下代码:

with open(in_file1,"r") as f1, open(in_file2,"r") as f2:
    for (line1, line2) in zip(f1, f2):
        compare(line1, line2)

但似乎python无法逐行读取文件。我观察到运行代码时的内存使用量 > 20G。我也试过使用:

import fileinput
for (line1, line2) in zip(fileinput.input([in_file1]),fileinput.input([in_file2])):
    compare(line1, line2)

这个也尝试将所有内容加载到内存中。我在 Centos 5.9 上使用 Python 2.7.4,我的代码中没有存储任何行。

我的代码出了什么问题?我应该如何更改它以避免将所有内容加载到 RAM 中?

【问题讨论】:

    标签: python file file-io


    【解决方案1】:

    Python 的 zip 函数返回一个 list 元组。因此,如果获取完整的文件来构建此列表。请改用 itertools.izip。它将返回元组的迭代器

    with open(in_file1,"r") as f1, open(in_file2,"r") as f2:
        for (line1, line2) in izip(f1, f2):
            compare(line1, line2)
    

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 1970-01-01
      • 2017-09-15
      • 2020-11-12
      • 2021-12-22
      • 2011-03-30
      • 1970-01-01
      • 2017-01-21
      相关资源
      最近更新 更多