我正在尝试确定某些文件的数据一致性。但是,MD5不断变化。当我执行时md5sum
,哈希值是相等的:
import hashlib
import os
import sys
def hash_file_content(path):
try:
if not os.path.exists(path):
raise IOError, "File does not exist"
encode = hashlib.md5(path).hexdigest()
return encode
except Exception, e:
print e
def main():
hash1 = hash_file_content("./downloads/sample_file_1")
hash2 = hash_file_content("./samples/sample_file_1")
print hash1, hash2
if __name__ == "__main__":
main()
输出意外地不同:
baed6a40f91ee5c44488ecd9a2c6589e 490052e9b1d3994827f4c7859dc127f0
现在带有md5sum
:
md5sum ./samples/sample_file_1
9655c36a5fdf546f142ffc8b1b9b0d93 ./samples/sample_file_1
md5sum ./downloads/sample_file_1
9655c36a5fdf546f142ffc8b1b9b0d93 ./downloads/sample_file_1
为什么会发生这种情况,我该如何解决?
在您的代码中,您正在计算md5
文件路径的,而不是文件内容的:
...
encode = hashlib.md5(path).hexdigest()
...
而是计算文件内容的md5:
with open(path, "r") as f:
encode = md5(f.read()).hexdigest()
并且这应该为您提供匹配的输出(即,彼此匹配并且与相同md5sum
)。
由于文件很大,因此f.read()
一次性执行会增加负担,并且在文件大小超出可用内存时根本无法工作。
因此,可以利用以下事实:在内部,md5使用其update方法来计算块上的哈希,并定义一个使用的方法md5.update
,并在代码中对其进行调用,如此答案所述:
import hashlib
def md5_for_file(filename, block_size=2**20):
md5 = hashlib.md5()
with open(filename, "rb") as f:
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.digest()
并立即在您的代码中调用此代码:
encode = md5_for_file(path)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句