linux有个命令叫做md5sum,能生成文件的md5值,一般情况下都会将结果记录到一个文件中用于校验使用,比如会这样使用:
[ crazyant @ localhost PythonMd5 ] $ more sample_file
www . crazyant . net
www . 51projob.com
[ crazyant @ localhost PythonMd5 ] $ md5sum sample_file > sample_file . md5file
[ crazyant @ localhost PythonMd5 ] $ more sample_file . md5file
311d384505e3622ccf85d88930e2b0a0 sample _file
[ crazyant @ localhost PythonMd5 ] $ md5sum - c sample_file . md5file
sample_file : OK
其中md5sum -c用于检测生成的md5值是否正确。
使用python生成文件md5值以及生成和md5sum结果一样的结果文件
python可以使用hashlib的md5模块对文件内容进行md5校验码生成,如果要生成和md5sum一样的结果文件,只需要将MD5结果值和文件名输出一行,中间有两个空格输出即可。
测试代码:
# -*- encoding:utf-8 -*-
from hashlib import md5
import os
def generate_file_md5value ( fpath ) :
'' '以文件路径作为参数,返回对文件md5后的值
' ''
m = md5 ( )
# 需要使用二进制格式读取文件内容
a_file = open ( fpath , 'rb' )
m . update ( a_file . read ( ) )
a_file . close ( )
return m . hexdigest ( )
def generate_file_md5sumFile ( fpath ) :
fname = os . path . basename ( fpath )
fpath_md5 = "%s.md5" % fpath
fout = open ( fpath_md5 , "w" )
fout . write ( "%s %s\n" % ( generate_file_md5value ( fpath ) , fname . strip ( ) ) )
print "generate success, fpath:%s" % fpath_md5
fout . flush ( )
fout . close ( )
if __name__ == "__main__" :
fpath = "/home/users/workbench/PythonMd5/sample_file"
# 测试一:以文件路径作为参数,获得md5后的字符串
print generate_file_md5value ( fpath )
# 测试二:生成和linux命令:md5sum同样结果的.md5文件
generate_file_md5sumFile ( fpath )
运行结果:
[ crazyant @ localhost PythonMd5 ] $ python generateMd5file . py
311d384505e3622ccf85d88930e2b0a0
generate success , fpath : / home / crazyant / workbench / PythonMd5 / sample_file . md5
[ crazyant @ localhost PythonMd5 ] $ md5sum - c sample_file . md5
sample_file : OK
注意点
在windows下开发的代码,如果直接提交到linux运行,经常因为windows下的换行符是\r\n而linux是\n的缘故导致代码执行失败,一般情况下都要进行一下转换。
标签:Python,crazyant,md5sum,校验,fpath,sample,file,md5 From: https://blog.51cto.com/peishuai/6042039