python文件的md5加密方法

WBOY
Release: 2016-06-10 15:05:26
Original
1702 people have browsed it

本文实例讲述了python文件的md5加密方法。分享给大家供大家参考,具体如下:

简单模式:

from hashlib import md5
def md5_file(name):
  m = md5()
  a_file = open(name, 'rb') #需要使用二进制格式读取文件内容
  m.update(a_file.read())
  a_file.close()
  return m.hexdigest()
if __main__ == '__init__':
  print md5_file('d:/test.txt')

Copy after login

大文件速度更快一点的方式

#!/usr/bin/python
#encoding=utf-8
import io
import sys
import hashlib
import string
def printUsage():
  print ('''''Usage: [python] pymd5sum.py <filename>''')
def main():
  if(sys.argv.__len__()==2):
    #print(sys.argv[1])
    m = hashlib.md5()
    file = io.FileIO(sys.argv[1],'r')
    bytes = file.read(1024)
    while(bytes != b''):
      m.update(bytes)
      bytes = file.read(1024)
    file.close()
    #md5value = ""
    md5value = m.hexdigest()
    print(md5value+"\t"+sys.argv[1])
    #dest = io.FileIO(sys.argv[1]+".CHECKSUM.md5",'w')
    #dest.write(md5value)
    #dest.close()
  else:
    printUsage()
main()

Copy after login

希望本文所述对大家Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template