首页 » Python » python计算文件md5sum

python计算文件md5sum

 
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import requests
import json
import hashlib
import sys
if len(sys.argv) != 2:
    print("need one parameter") 
    exit(0)

url = sys.argv[1]
base_url = url.rsplit('/',1)[0]



def GetMD5FromLocalFile(filename):
    """
    Get local file's MD5 Info.
    @param filename:file path & file name
    @return:MD5 Info
    """
    file_object = open(filename, 'rb')
    file_content = file_object.read()
    file_object.close()
    file_md5 = hashlib.md5(file_content)
    return file_md5.hexdigest()

def compare_zip_md5(url,base_url):
	r = requests.get(url)
	with open('v31.json','wb') as f:
		f.write(r.content)
	with open('v31.json','r') as f2:
		f1 = json.load(f2)
	l1 = f1['xlist']
	for n in l1:
	 	url1 = base_url + '/' +  n[1]	
		r1 = requests.get(url1)
		with open(n[1],'wb') as f3:
			f3.write(r1.content)
		file_md5 = GetMD5FromLocalFile(n[1])
		file_md5 = file_md5.upper()
		if file_md5 != n[2]:
			print("this is error: %s"%n[1])

if __name__ == "__main__":
	compare_zip_md5(url,base_url)

当文件比较大的时候,可以使用下面的方法来计算:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import sys
if len(sys.argv) != 2:
    print("need one parameter") 
    exit(0)
file_path = sys.argv[1]

def get_file_md5(fname):
    m = hashlib.md5()   
    with open(fname,'rb') as fobj:
        while True:
            data = fobj.read(4096)
            if not data:
                break
            m.update(data)  

    return m.hexdigest()   

if __name__ == '__main__':
    file_md5 = get_file_md5(file_path)
    print(file_md5) 

原文链接:python计算文件md5sum,转载请注明来源!

0