gpt4 book ai didi

python - 在Python中比较两个大文件

转载 作者:太空狗 更新时间:2023-10-29 21:51:03 24 4
gpt4 key购买 nike

我有两个大文本文件,每个文件接近 2GB。我需要像 diff f1.txt f2.txt 这样的东西。有什么办法可以在 python 中快速完成这项任务吗?标准 difflib 太慢了。我认为有更快的方法,因为 difflib 完全用 Python 实现。

最佳答案

以脚本可以处理大文件的方式使用 difflib 怎么样?不要将文件加载到内存中,而是遍历文件的文件和 block 中的差异。例如一次 100 行。

import difflib

d = difflib.Differ()

f1 = open('bigfile1')
f2 = open('bigfile2')

b1 = []
b2 = []

for n, lines in enumerate(zip(f1,f2)):
if not (n % 100 == 0):
b1.append(lines[0])
b2.append(lines[1])
else:
diff = d.compare("".join(b1), "".join(b2))
b1 = []
b2 = []
print ''.join(list(diff))

diff = d.compare("".join(b1), "".join(b2))
print ''.join(list(diff))
f1.close()
f2.close()

关于python - 在Python中比较两个大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4899146/

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