为 Python 中的多个文件生成一个 MD5/SHA1 校验和

Generating one MD5/SHA1 checksum of multiple files in Python

我浏览了 Python 中关于计算文件校验和的几个主题,但其中 none 回答了关于多个文件的一个总和的问题。我在子目录中有几个文件,想确定其中一个或多个文件是否有任何更改。 有没有办法从多个文件生成一个总和?

编辑: 这是我获取总和列表的方法:

checksums = [(fname, hashlib.md5(open(fname, 'rb').read()).digest()) for fname in flist]

所以我做到了:) 这样就为文件列表生成了一个哈希和。

hash_obj = hashlib.md5(open(flist[0], 'rb').read())
for fname in flist[1:]:
    hash_obj.update(open(fname, 'rb').read())
checksum = hash_obj.digest()

谢谢 PM 2Ring 的意见!

请注意,md5 已被破解,因此仅将其用于非安全关键目的。

比 Artur 的回答稍微干净一些。第一个元素不用特殊处理

def calculate_checksum(filenames):
    hash = hashlib.md5()
    for fn in filenames:
        if os.path.isfile(fn):
            hash.update(open(fn, "rb").read())
    return hash.digest()

(如果您愿意,可以删除 os.path.isfile()。)

import subprocess
cmd =input("Enter the command : ")
trial = subprocess.run(["powershell","-Command",cmd])
#Powershell command : Get-FileHash -Algorithm MD5 -Path (Get-ChildItem "filepath\*.*" -Recurse -force)