繁体   English   中英

如何在 python 中散列 sha256 后保存 output file.txt

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM