python分别生成字符串、文件、目录的MD5编码

2022-03-11 00:00:00 字符串 生成 编码

python分别生成字符串、文件、目录的MD5编码

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/28
功能描述:
"""
from hashlib import md5


def calMD5(str):
    m = md5()
    m.update(str)
    return m.hexdigest()


def calMD5ForFile(file):
    m = md5()
    a_file = open(file, 'rb')
    m.update(a_file.read())
    a_file.close()
    return m.hexdigest()


def calMD5ForFolder(dir, MD5File):
    import os
    outfile = open(MD5File, 'w')
    for root, subdirs, files in os.walk(dir):
        for file in files:
            filefullpath = os.path.join(root, file)
            print(filefullpath)
            filerelpath = os.path.relpath(filefullpath, dir)
            md5 = calMD5ForFile(filefullpath)
            outfile.write(filerelpath + ' ' + md5 + '\n')
    outfile.close()


print(calMD5('测试字符串:https://www.pidancode.com'.encode('utf-8')))
print(calMD5ForFile('./pidancode.com.txt'))
calMD5ForFolder('./test', './mdfile.md5')

输出如下:
a01c35b949c9a7c7d48bff6edf6a5c30
a4c3b3bca20b487756107be2a2f3e78d

以上代码在Python3.9下测试通过。

相关文章