生成文件的MD5校验和 [英] Generating an MD5 checksum of a file

查看:222
本文介绍了生成文件的MD5校验和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何简单的方法来生成(和检查)Python中文件列表的MD5校验和? (我正在开发一个小程序,我想确认文件的校验和.)

Is there any simple way of generating (and checking) MD5 checksums of a list of files in Python? (I have a small program I'm working on, and I'd like to confirm the checksums of the files).

推荐答案

您可以使用 hashlib.md5 ()

请注意,有时您将无法在内存中容纳整个文件.在这种情况下,您将必须顺序读取4096个字节的块并将其提供给md5方法:

Note that sometimes you won't be able to fit the whole file in memory. In that case, you'll have to read chunks of 4096 bytes sequentially and feed them to the md5 method:

import hashlib
def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

注意: hash_md5.hexdigest()将返回摘要的 hex字符串表示形式,如果您只需要使用return hash_md5.digest()打包的字节,则无需转换回来.

Note: hash_md5.hexdigest() will return the hex string representation for the digest, if you just need the packed bytes use return hash_md5.digest(), so you don't have to convert back.

这篇关于生成文件的MD5校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆