我试图编写一个脚本,为指定根目录中的所有文件名和目录名生成哈希值。 这是我目前为止的剧本:
import hashlib
import os
import sys
class Hasher:
def __init__(self):
self.hash_func = hashlib.md5()
def hash_file(self, file_path):
with open(file_path, "rb") as file:
self.hash_func.update(file.read())
return self.hash_func.digest()
def hash_dir(self, dir_path):
for dirpath, dirnames, filenames in os.walk(dir_path):
self.hash_func.update(dirpath.encode("utf-8"))
for file_path in filenames:
self.hash_func.update(file_path.encode("utf-8"))
return self.hash_func.digest()
hasher = Hasher()
root_dir = "D:/folder/"
hash_1 = str(hasher.hash_dir(root_dir))
hash_2 = str(hasher.hash_dir(root_dir))
print(hash_1)
print(hash_2)
由于某些原因,它为同一个目录生成两个不同的哈希值,而不会对目录进行任何更改。如果目录保持不变,我如何使它产生相同的哈希值?在
问题是
hashlib.md5
对象每次都会被重用,因此返回累积数据的散列值,而不仅仅是上一个/预期的数据。在您可以通过每次创建一个新的
Hasher
对象来解决这个问题(因此在本例中调用Hasher().hash_dir(root_dir)
两次)。但是由于您的Hasher
类只包含md5
对象和两个可能是静态的方法之外的任何其他数据,我建议将这两个类方法都设为静态的,并在方法本身中创建hashlib.md5
对象:相关问题 更多 >
编程相关推荐