# 计算文件的md5有两种方法 # 1、如果是大文件的话,可以采用循环每次读一部分数据,然后计算md5 t1 = time.time() for i in range(10000): md5 = hashlib.md5(bytes("123", encoding="utf-8")) with open("new.json","rb") as f: while True: temp = f.read(1) if temp: md5.update(temp) else: break t2 = time.time() print(t2 - t1) # 如果是小文件,可以直接把文件到读到内存中,直接计算md5 t1 = time.time() for m in range(10000): md5 = hashlib.md5(bytes("123", encoding="utf-8")) file = open("new.json", "r") md5.update(bytes(file.read(),encoding="utf-8")) t2 = time.time() print(t2 - t1)
这里执行了10000次,主要为了统计2种方法那种速度更快