您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用Python计算文件系统目录的哈希值?

如何使用Python计算文件系统目录的哈希值?

食谱提供了一个很好的功能来完成您要问的事情。我已将其修改为使用MD5哈希而不是SHA1,正如您的原始问题所要求的那样

def GetHashofDirs(directory, verbose=0):
  import hashlib, os
  SHAhash = hashlib.md5()
  if not os.path.exists (directory):
    return -1

  try:
    for root, dirs, files in os.walk(directory):
      for names in files:
        if verbose == 1:
          print 'Hashing', names
        filepath = os.path.join(root,names)
        try:
          f1 = open(filepath, 'rb')
        except:
          # You can't open the file for some reason
          f1.close()
          continue

        while 1:
          # Read file in as little chunks
          buf = f1.read(4096)
          if not buf : break
          SHAhash.update(hashlib.md5(buf).hexdigest())
        f1.close()

  except:
    import traceback
    # Print the stack traceback
    traceback.print_exc()
    return -2

  return SHAhash.hexdigest()

您可以像这样使用它:

print GetHashofDirs('folder_to_hash', 1)

输出看起来像这样,因为它哈希了每个文件

...
Hashing file1.cache
Hashing text.txt
Hashing library.dll
Hashing vsfile.pdb
Hashing prog.cs
5be45c5a67810b53146eaddcae08a809

函数调用返回的值以哈希形式返回。在这种情况下,5be45c5a67810b53146eaddcae08a809

python 2022/1/1 18:49:36 有384人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶