我想在 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)))
Run Code Online (Sandbox Code Playgroud)
正确的做法(可能)是为每个目录重复计算哈希值,如下所示:
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)))
Run Code Online (Sandbox Code Playgroud)
仅使用按顺序os.walk
提供的文件的问题(就像 Markus 所做的那样)是,对于包含相同文件的不同文件结构,您可能会获得相同的哈希值。例如,这个目录的哈希值
main_dir_1:
dir_1:
file_1
file_2
dir_2:
file_3
Run Code Online (Sandbox Code Playgroud)
和这个
main_dir_2:
dir_1:
file_1
dir_2:
file_2
file_3
Run Code Online (Sandbox Code Playgroud)
会是一样的。
另一个问题是,您需要保证文件的顺序始终相同 - 如果您以不同的顺序连接两个哈希值并计算得到的字符串的哈希值,对于相同的目录结构,您将得到不同的结果。