用Python计算某个目录下所有文件的hash

This script can calculate all files' hash value on a folder, 

import hashlib
import os


def cal_file_sha256(filt_path):
    with open(filt_path, "rb") as f:
        file_hash = hashlib.sha256()
        while chunk := f.read(1024 * 1024):
            file_hash.update(chunk)
    return file_hash.hexdigest()


def cal_folder_hash(folder):
    if not os.path.exists(folder):
        print("Folder doesn't exist %s" % folder)
        return
    for file in os.listdir(folder):
        path = os.path.join(folder, file)
        if os.path.isdir(path):
            cal_folder_hash(path)
        else:
            print("File: %s" % path)
            sha256 = cal_file_sha256(path)
            print("SHA256: %s\n" % sha256)


if __name__ == "__main__":
    cal_folder_hash("D:/Docs/study/python")

 

你可能感兴趣的:(python)