该食谱提供了一个很好的功能来完成您要问的事情。我已将其修改为使用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.cacheHashing text.txtHashing library.dllHashing vsfile.pdbHashing prog.cs5be45c5a67810b53146eaddcae08a809
此函数调用返回的值以哈希形式返回。在这种情况下,
5be45c5a67810b53146eaddcae08a809



