gpt4 book ai didi

python - 在python中查看两个文件是否具有相同的内容

转载 作者:IT老高 更新时间:2023-10-28 20:37:45 25 4
gpt4 key购买 nike

Possible Duplicates:
Finding duplicate files and removing them.
In Python, is there a concise way of comparing whether the contents of two text files are the same?

在 Python 中查看两个文件在内容方面是否相同的最简单方法是什么。

我可以做的一件事是 md5 每个文件并进行比较。有没有更好的办法?

最佳答案

是的,如果您必须比较多个文件并存储哈希值以供以后比较,我认为对文件进行哈希处理是最好的方法。由于哈希可能会发生冲突,因此可以根据用例进行逐字节比较。

通常逐字节比较就足够且高效,filecmp 模块已经做了 + 其他事情。

http://docs.python.org/library/filecmp.html例如

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

速度考虑:通常,如果只需要比较两个文件,那么散列并比较它们会更慢,而不是简单的逐字节比较,如果有效地完成的话。例如下面的代码尝试对哈希和逐字节进行计时

免责声明:这不是计时或比较两种算法的最佳方式。并且需要改进,但它确实给出了粗略的想法。如果您认为它应该改进,请告诉我我会改变它。

import random
import string
import hashlib
import time

def getRandText(N):
return "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
hash1 = hashlib.md5()
hash1.update(text1)
hash1 = hash1.hexdigest()

hash2 = hashlib.md5()
hash2.update(text2)
hash2 = hash2.hexdigest()

return hash1 == hash2

def cmpByteByByte(text1, text2):
return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
st = time.time()
for i in range(10):
cmpFunc(randText1, randText2)
print cmpFunc.func_name,time.time()-st

输出是

cmpHash 0.234999895096
cmpByteByByte 0.0

关于python - 在python中查看两个文件是否具有相同的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1072569/

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