Python Forum

Full Version: how to generate sha256 hash for each line of my txt file | using python version 3.6.4
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am creating a project for generating sha256 hash from text file
I want to read each line from my text file and generate sha256 for it.

Here is the code i written but it is not correct. please see and suggest me.
my text file contains:
apple
banana
grape
watermelon
stawberry

my Code is :
import hashlib
f = open("D:/12/1.txt",'r')
x = f.readline()
while(x !=""):
    hash_object = hashlib.sha256(b'x')
    hex_dig = hash_object.hexdigest()
    print(x.strip(),"",hex_dig)
    x= f.readline()

input("Successful..Press enter to exit")
This should do it.
import hashlib

with open('fruit.txt') as f:
    for line in f:
        line = line.strip()
        print(f'{hashlib.sha256(line.encode()).hexdigest()} --> {line}')
Output:
3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b --> apple b493d48364afe44d11c0165cf470a4164d1e2609911ef998be868d46ade3de4e --> banana 0f78fcc486f5315418fbf095e71c0675ee07d318e5ac4d150050cd8e57966496 --> grape 31a2d5282683edb3a22c565f199aa96fb9ffb3107af35aad92ee1cd567cfc25d --> watermelon e8c40ad2555f8a601a4946ab395a2e840bf8a96d8e7b0a66e747c97033b716af --> stawberry
If my list contain some more lines like 100 words or more.
if i want to output a line in my output.txt --for-- Which sha256 starts with the prefix 'e8'
So its output the raw text & sha256 in output.txt