【Python】计算文件MD5 和 SHA1

      不多说,直接源码:

#file md5
import sys;  
import hashlib;  
import os.path;
  
def GetFileMd5(strFile):
	file = None;
	bRet = False;
	strMd5 = "";
	strSha1 = "";
	try:
		file = open(strFile, "rb");
		md5 = hashlib.md5();
		sha1 = hashlib.sha1();
		strRead = "";
		while True:  
			strRead = file.read(8096);  
			if not strRead:
				break;
			else:
				md5.update(strRead);
				sha1.update(strRead);
		#read file finish
		bRet = True;
		strMd5  = md5.hexdigest();
		strSha1 = sha1.hexdigest();
	except:
		bRet = False;
	finally:
		if file:
			file.close()
	return [bRet, strMd5, strSha1];
	
def writFile(strInfo):
	file = None;
	file = open("E:\\1.txt", 'w+');
	file.write(strInfo);
	file.write("\n");
	if file:
		file.close();

  
if "__main__" == __name__:  
   bOK , md5str1, sha1str1 = GetFileMd5("E:\\1.mp3");
   print(md5str1);
   md5All = md5str1 + "\t" + sha1str1;
   md5All += "\n";
   
   bOK , md5str2, sha1str2 = GetFileMd5("E:\\2.mp3");
   print(md5str2);
   writFile(md5str2 + "\t" +sha1str2);
   md5All += (md5str2 + "\t" + sha1str2);
   md5All += "\n";
   
   bOK , md5str3, sha1str3 = GetFileMd5("E:\\3.mp3");
   print(md5str3);
   writFile(md5str3 + "\t" +sha1str3);
   md5All += (md5str2 + "\t" + sha1str3);
   md5All += "\n";
   
   writFile(md5All);
   

产生的文件如下:

e712ca35354ff51803b51f3c7db03a81	8417609d07ce1bbd53111f1664ecfb63422749bb
34d7451ef9fbeb4c1ebbf2ed5cb96329	9d7009e1f1cd750f5a795d25491a5d294a45f3b2
34d7451ef9fbeb4c1ebbf2ed5cb96329	8a11f608aee135dd1d4b8c64af0721790e0a0b32

要是自己使用,改吧,改吧就可以使用了。

你可能感兴趣的:(Python)