[英]how to save output file.txt after hashing sha256 in python
我正在嘗試使用 python 對 hash sha256。 我得到了這樣的結果,但我不知道如何將 hash 結果保存到 file.txt。 請幫我編輯命令。
import hashlib
with open('x.txt') as f:
for line in f:
line = line.strip()
print(hashlib.sha256(line.encode()).hexdigest())
9869f9826306f436e1a8581b7ce467d38bab6e280839fd88fd51d45de39b6409 b51d80a47274161a0eeb44cfa1586ee9c4bc3d33740895a4d688f9090e24d8c2 f0f2ea3096f72e0d6916f9febd912a17fd9c91e83dd9e558967e21329dfbe393 4799d169d99c206ae68fe96c67736d88b6976c1a47ce2383ced8de9edf41ade9 2a68d417af41750b17a1b65b2002c5875b2b40232d54f7566e1fc51f5395b9f9 826c4d573dc5766eb44461f76ce0ca08487e9d5894583214b7c52bdf032039c4
像這樣的結果[1]: https://i.stack.imgur.com/DBj1p.png
只需要open
帶有w
標志的文件並寫入即可。
請參閱有關Reading and Writing Files
的文檔。
import hashlib
with open('x.txt') as f_in, open('file.txt', 'w') as f_out:
for line in f_in:
line = line.strip()
f_out.write(hashlib.sha256(line.encode()).hexdigest())
PS。 你沒有正確散列文件,你不應該使用line.strip()
因為這意味着你 hash 沒有前導/尾隨空格/制表符/換行符的行。
import hashlib
with open('x.txt') as f:
for line in f:
line = line.strip()
txt_to_write = hashlib.sha256(line.encode()).hexdigest())
with open('readme.txt', 'w') as f:
f.write(txt_to_write)
您必須創建一個文件並寫入其中。 您將 hash 的結果放入變量中並編寫它。 在這里,文件將在您當前的存儲庫中創建。
您打開了一個文件('x.txt')以逐行讀取,因此您需要打開另一個文件來寫入 output。
你可以一行一行地寫:
import hashlib
with open("x.txt") as f:
with open("file.txt", "w") as outfile:
for line in f:
line = line.strip()
hash = hashlib.sha256(line.encode()).hexdigest()
outfile.write(hash + "\n")
或者你可以定義一個列表,append 每行,寫一次:
import hashlib
hashes = []
with open("x.txt") as f:
for line in f:
line = line.strip()
hash = hashlib.sha256(line.encode()).hexdigest()
hashes.append(hash + "\n")
with open("file.txt", "w") as outfile:
outfile.writelines(hashes)
請注意,您需要 append "\n" 跳轉到新行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.