使用hashlib的md5方法對文件進行加密,目的是為了保證文件在傳輸的過程中是否發生變化。
#!/usr/bin/python3 # coding:utf-8 # Auther:AlphaPanda # Description:使用hashlib模塊,對文件內容進行校驗。以此來判斷文件傳輸過程中是否發生變化,或者有損壞 # Version:1 # Date:Fri Dec 6 22:15:16 EST 2019 import hashlib # 針對小文件的內容校驗 def check_md5(file): with open(file,mode="rb") as fp: res = fp.read() hs = hashlib.md5() hs.update(res) return hs.hexdigest() res = check_md5("ceshi1.txt") print(res) # 針對大文件的內容校驗 hs = hashlib.md5() hs.update("你好\n世界".encode()) print(hs.hexdigest()) hs = hashlib.md5() hs.update("你好".encode()) hs.update("\n世界".encode()) print(hs.hexdigest()) # 通過以上實驗,證明一次加密文件的一行,依次加密完所有的文件內容和一次加密所有的文件內容,所獲得的hash值一樣。 # 大文件校驗方法1: def check2_md5(file): hs = hashlib.md5() with open(file,mode="rb") as fp: while True: content = fp.read(3) if content: hs.update(content) else: break return hs.hexdigest() print(check2_md5("ceshi3.txt")) # 方法二: import os def check4_md5(file): # 計算文件大小 file_size = os.path.getsize(file) hs = hashlib.md5() with open(file,mode="rb") as fp: while file_size: # 一次最多讀取三個字節 content = fp.read(3) hs.update(content) file_size -= len(content) return hs.hexdigest() print(check4_md5("ceshi4.txt"))