获取文件的md5值

有时为了文件传输的安全,需要对文件进行加密以进行更好的传输。所以在本地进行脚本编写以便获得文件md5值。

# coding=UTF-8 

import hashlib
import os
import datetime

def GetFileMd5(filename):
    #如果path是一个存在的文件,返回True。否则返回False。
    if os.path.isfile(filename):
        # 输出文件的md5值以及记录运行时间
        starttime = datetime.datetime.now()
        #hashlib进行字符md5加密
        myhash = hashlib.md5()
        f = open(filename,'rb')
        while True:
            b = f.read(8096)
            if not b :
                break
            myhash.update(b)
        f.close()
        return myhash.hexdigest()
        endtime = datetime.datetime.now()
        print u'运行时间:%ds'%((endtime-starttime).seconds)
    else:
        return u'输入的非文件路径!'

if __name__ == '__main__':
    #获取需要获取md5的文件,这里进行编码转换,否则输出为乱码
    filepath = raw_input(unicode('请输入文件路径:','utf-8').encode('gbk'))
    print GetFileMd5(filepath)

使用本地的ip.txt进行测试比对:

本地文件测试:

测试地址: http://www.atool.org/file_hash.php

测试截图:

获取文件的md5值_第1张图片

参考地址:https://www.cnblogs.com/yym2013/p/5482796.html

 

你可能感兴趣的:(python)