Python3计算MD5值(包括字符串、文件、文件夹)

Python3计算MD5值(包括字符串、文件、文件夹)

  • python3下没有md5这个模块,需要导入hashlib这个包
  • 参考
  • 程序如下:
import os
import hashlib
import random


def get_md5_of_string(src):
    """
    get md5 of a string
    :param src:
    :return:
    """
    md1 = hashlib.md5()
    md1.update(src.encode('UTF-8'))
    return md1.hexdigest()


def get_md5_of_file(filename):
    """
    get md5 of a file
    :param filename:
    :return:
    """
    if not os.path.isfile(filename):
        return None
    myhash = hashlib.md5()
    with open(filename, 'rb') as f:
        while True:
            b = f.read(8096)
            if not b:
                break
            myhash.update(b)
    return myhash.hexdigest()


def get_md5_of_folder(dir_):
    """
    get md5 of a folder
    :param dir_:
    :return:
    """
    if not os.path.isdir(dir_):
        return None
    MD5File = "{}_tmp.md5".format(str(random.randint(0, 1000)).zfill(6))
    with open(MD5File, 'w') as outfile:
        for root, subdirs, files in os.walk(dir_):
            for file in files:
                filefullpath = os.path.join(root, file)
                md5 = get_md5_of_file(filefullpath)
                outfile.write(md5)
    val = get_md5_of_file(MD5File)
    os.remove(MD5File)
    return val

你可能感兴趣的:(Python,python)