我正在使用此代码计算文件的哈希值:
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
当我在文件夹"文件夹"上尝试时,我得到了
IOError: [Errno 13] Permission denied: folder
我怎么能计算文件夹的哈希值?
使用checksumdir python包可用于计算目录的校验和/哈希.它可以在https://pypi.python.org/pypi/checksumdir/1.0.5上找到
用法:
import checksumdir hash = checksumdir.dirhash("c:\\temp") print hash
这个食谱提供了一个很好的功能来做你要求的.我已修改它以使用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