我想在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
会是一样的。
另一个问题是,您需要保证文件的顺序始终相同-如果以不同的顺序合并两个散列并计算所获得的字符串的散列,则对于相同的目录结构,您将获得不同的结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句