且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-29 14:42:52

配方提供了一个很好的功能来完成你所要求的功能。我已经修改它以使用MD5散列,而不是SHA1,因为您原来的问题是要求

  def GetHashofDirs(directory, 
import hashlib,os
SHAhash = hashlib.md5()
如果不是os.path.exists(目录):
返回-1

尝试:
用于root,dirs,os.walk(目录)中的文件:
用于文件中的名称:
if verbose == 1:
print'哈希',命名
filepath = os.path.join(root,names)
try:
f1 = open(filepath,'rb')
除外:
#由于某些原因,您无法打开该文件
f1.close()
continue

while 1:
#以小块形式读取文件
buf = f1.read(4096)
如果不是buf:break
SHAhash.update(hashlib.md5(buf).hexdigest())
f1.close()

除外:
导入追踪
#打印堆栈
traceback.print_exc()
返回-2

返回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


I'm using this code to calculate hash value for a file:

m = hashlib.md5()
with open("calculator.pdf", 'rb') as fh:
    while True:
        data = fh.read(8192)
        if not data:
            break
        m.update(data)
    hash_value = m.hexdigest()

    print  hash_value

when I tried it on a folder "folder"I got

IOError: [Errno 13] Permission denied: folder

How could I calculate the hash value for a folder ?

This Recipe provides a nice function to do what you are asking. I've modified it to use the MD5 hash, instead of the SHA1, as your original question asks

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()

You can use it like this:

print GetHashofDirs('folder_to_hash', 1)

The output looks like this, as it hashes each file:

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

The returned value from this function call comes back as the hash. In this case, 5be45c5a67810b53146eaddcae08a809