2014-10-18 101 views
1

我正在嘗試創建一個名爲checksum.dat的文件,其中包含Python中名爲index.txt的文件的SHA256哈希。如何從Python中的.txt文件生成checksum.dat哈希文件

我想出迄今:

import hashlib 
with open("index.txt", "rb") as file3: 
    with open("checksum.dat", "wb") as file4: 
     file_checksum = hashlib.sha256() 
     file_checksum.update(file3) 
     file_checksum.digest() 

     print(file_checksum) 
     file4.write(file_checksum) 

我希望它打印散列到控制檯,並把它寫到文件checksum.dat。

但我得到的是這樣的錯誤:

File "...", line 97, in main 
file_checksum.update(file3) 
TypeError: object supporting the buffer API required 

什麼我GOOGLE到目前爲止是,你不能讓一個哈希出一個字符串,從我的理解,只能從字節對象或東西。不知道如何將我的index.txt放入我可以使用的對象中。

任何人都知道如何解決這個問題?請記住我是一個新手。

+0

其中Python版本是你的工作嗎? – 2014-10-18 13:38:16

+0

我關於Python 3.4.2 – LoLei 2014-10-18 14:22:01

回答

0

你必須養活index.txt內容,所以問題就出在這裏:

file_checksum.update(file3) 

file3是文件指針index.txt文件並沒有文件的內容。要獲取內容,請執行read()。所以下面應該修復它:

file_checksum.update(file3.read()) 

所以,你的完整代碼如下:

import hashlib 
with open("index.txt", "rb") as file3: 
     file_checksum = hashlib.sha256() 
     for line in file3: 
      file_checksum.update(line) 
      file_checksum.hexdigest() 
     print(file_checksum.hexdigest()) 

with open("checksum.dat", "wb") as file4:   
     file4.write(bytes(file_checksum.hexdigest(), 'UTF-8')) 
+0

現在,我得到以下異常: 'file4.write(file_checksum) 類型錯誤:「_hashlib.HASH」不支持interface' – LoLei 2014-10-18 14:26:23

+0

緩衝區不讀取整個文件一次,否則你的程序將窒息大輸入。另外,不要使用'encode()',因爲它可能會改變原始表示(以及哈希碼)。 – 2014-10-18 14:32:53

+0

@StefanoSanfilippo - 更新了答案,現在它逐行讀取並計算校驗和。如果您有任何其他建議,請告訴我。 – avi 2014-10-18 14:48:51