我想在 python 中为给定目录创建一个唯一的散列。感谢 zmo 下面的代码为目录中的每个文件生成哈希,但我如何聚合这些代码以生成单个哈希来表示文件夹?
import os
import hashlib
def sha1OfFile(filepath):
sha = hashlib.sha1()
with open(filepath, 'rb') as f:
while True:
block = f.read(2**10) # Magic number: one-megabyte blocks.
if not block: break
sha.update(block)
return sha.hexdigest()
for (path, dirs, files) in os.walk('.'):
for file in files:
print('{}: {}'.format(os.path.join(path, file),
sha1OfFile(os.path.join(path, file)))
正确的做法(可能)是像这样为每个目录递归计算哈希值:
import os
import hashlib
def sha1OfFile(filepath):
sha = hashlib.sha1()
with open(filepath, 'rb') as f:
while True:
block = f.read(2**10) # Magic number: one-megabyte blocks.
if not block: break
sha.update(block)
return sha.hexdigest()
def hash_dir(dir_path):
hashes = []
for path, dirs, files in os.walk(dir_path):
for file in sorted(files): # we sort to guarantee that files will always go in the same order
hashes.append(sha1OfFile(os.path.join(path, file)))
for dir in sorted(dirs): # we sort to guarantee that dirs will always go in the same order
hashes.append(hash_dir(os.path.join(path, dir)))
break # we only need one iteration - to get files and dirs in current directory
return str(hash(''.join(hashes)))
按照 os.walk
给你的顺序只使用文件的问题(就像 Markus 所做的那样)是你可能会为包含相同文件的不同文件结构获得相同的哈希值。例如,这个目录的哈希
main_dir_1:
dir_1:
file_1
file_2
dir_2:
file_3
还有这个
main_dir_2:
dir_1:
file_1
dir_2:
file_2
file_3
将是相同的。
另一个问题是你需要保证文件的顺序总是相同的——如果你以不同的顺序连接两个哈希值并计算你得到的字符串的哈希值,你将得到相同目录结构的不同结果。