python - 在 python 中为目录创建唯一哈希

标签 python hash

<分区>

我想在 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

将是相同的。


另一个问题是你需要保证文件的顺序总是相同的——如果你以不同的顺序连接两个哈希值并计算你得到的字符串的哈希值,你将得到相同目录结构的不同结果。

关于python - 在 python 中为目录创建唯一哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36204248/

相关文章:

java - 为什么Java中的hashcode不用long来存储hash值?

ruby - Ruby(和其他语言)中哈希的良好显式命名风格

python - 如何在 python 中过滤和打印特定的 json 字典

python - PySpark - 按数组列分组

Python 无法从命令行找到模块,但可以从 Eclipse 中找到

python - 解决行之间的互补缺失值

javascript - 为什么 crypto.createHash 在新版本中返回不同的输出?

python - 如何在 Python 中使用 numpy.percentile() 计算置信区间

ruby - 从哈希数组中的哈希中获取 id

c# - SQL bigint 哈希匹配 c# int64 哈希