This article mainly introduces the md5 encryption method for python files, and involves Python's skills in reading files and encrypting strings, for more information about how to encrypt python files, see the following example. We will share this with you for your reference. The details are as follows:
Simple mode:
From hashlib import md5def md5_file (name): m = md5 () a_file = open (name, 'rb') # Read File Content in binary format m. update (a_file.read () a_file.close () return m. hexdigest () if _ main _ = '_ init _': print md5_file ('d:/test.txt ')
Faster speed of large files
#!/usr/bin/python#encoding=utf-8import ioimport sysimport hashlibimport stringdef printUsage(): print ('''''Usage: [python] pymd5sum.py
''')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()
I hope this article will help you with Python programming.