本文实例讲述了python文件的md5加密方法。分享给大家供大家参考,具体如下:
简单模式:
1
2
3
4
5
6
7
8
9
|
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' )
|
大文件速度更快一点的方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#!/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()
|
希望本文所述对大家Python程序设计有所帮助。