本文實例講述了Python實現通過文件路徑獲取文件hash值的方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import hashlib import os,sys def CalcSha1(filepath): with open (filepath, 'rb' ) as f: sha1obj = hashlib.sha1() sha1obj.update(f.read()) hash = sha1obj.hexdigest() print ( hash ) return hash def CalcMD5(filepath): with open (filepath, 'rb' ) as f: md5obj = hashlib.md5() md5obj.update(f.read()) hash = md5obj.hexdigest() print ( hash ) return hash if __name__ = = "__main__" : if len (sys.argv) = = 2 : hashfile = sys.argv[ 1 ] if not os.path.exists(hashfile): hashfile = os.path.join(os.path.dirname(__file__),hashfile) if not os.path.exists(hashfile): print ( "cannot found file" ) else CalcMD5(hashfile) else : CalcMD5(hashfile) #raw_input("pause") else : print ( "no filename" ) |
使用Python進行文件Hash計算有兩點必須要注意:
1、文件打開方式一定要是二進制方式,既打開文件時使用b模式,否則Hash計算是基于文本的那將得到錯誤的文件Hash(網上看到有人說遇到Python的Hash計算錯誤在大多是由于這個原因造成的)。
2、對于MD5
如果需要16位(bytes)的值那么調用對象的digest()
而hexdigest()
默認是32位(bytes),同理Sha1
的digest()
和hexdigest()
分別產生20位(bytes)和40位(bytes)的hash值
希望本文所述對大家Python程序設計有所幫助。