how to save output file.txt after hashing sha256 in python - python

I am trying to hash sha256 using python.
I got the result like this but I don't know how to save the hash result to file.txt. Please help me to edit the command.
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
results like this
[1]: https://i.stack.imgur.com/DBj1p.png

Just need to open the file with the w flag and write to it.
See the documentation on 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. you're not hashing the file properly, you should not use line.strip() as it means you hash the line without leading/trailing spaces/tabs/newlines.

You have one file ('x.txt') opened to read line by line, so you'll need to open another file to write your output.
You could write line by line:
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")
Or you could define a list, append every line, and write once:
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)
Note that you would need to append "\n" to jump to a new line.

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)
You have to create a file and write in it.
You put the result of your hash in a variable and you write it.
Here the file will be created in your current repository.

Related

Write() starts halfway through

I am new to python and I really don't understand why this is happening: when I run my code, the lower() is only applied to half (or less) of the text file. How I can fix this?
import glob, os, string, re
list_of_files = glob.glob("/Users/louis/Downloads/assignment/data2/**/*.txt")
for file_name in list_of_files:
f = open(file_name, 'r+')
for line in f:
line = line.lower()
f.write(line)
The problem is most probably because you are reading and writing at the same time. And you need to return to the start of the file to write in place of the original content. Try this:
for file_name in list_of_files:
with open(file_name, 'r+') as f:
content = f.read().lower()
f.seek(0, 0) # returns to the start of the file
f.write(content)

on opening a data file to reading the lines included in that file

I am using the following code segment to partition a data file into two parts:
def shuffle_split(infilename, outfilename1, outfilename2):
with open(infilename, 'r') as f:
lines = f.readlines()
lines[-1] = lines[-1].rstrip('\n') + '\n'
shuffle(lines)
with open(outfilename1, 'w') as f:
f.writelines(lines[:90000])
with open(outfilename2, 'w') as f:
f.writelines(lines[90000:])
outfilename1.close()
outfilename2.close()
shuffle_split(data_file, training_file,validation_file)
Running this code segment cause the following error,
in shuffle_split
with open(infilename, 'r') as f:
TypeError: coercing to Unicode: need string or buffer, file found
What's wrong with the way of opening the data_file for input?
Whatever you're passing in as infilename is already a file, rather than a file's path name.

Read txt files, results in empty lines

I have some problem to open and read a txt-file in Python. The txt file contains text (cat text.txt works fine in Terminal). But in Python I only get 5 empty lines.
print open('text.txt').read()
Do you know why?
I solved it. Was a utf-16 file.
print open('text.txt').read().decode('utf-16-le')
if this prints the lines in your file then perhaps the file your program is selecting is empty? I don't know, but try this:
import tkinter as tk
from tkinter import filedialog
import os
def fileopen():
GUI=tk.Tk()
filepath=filedialog.askopenfilename(parent=GUI,title='Select file to print lines.')
(GUI).destroy()
return (filepath)
filepath = fileopen()
filepath = os.path.normpath(filepath)
with open (filepath, 'r') as fh:
print (fh.read())
or alternatively, using this method of printing lines:
fh = open(filepath, 'r')
for line in fh:
line=line.rstrip('\n')
print (line)
fh.close()
or if you want the lines loaded into a list of strings:
lines = []
fh = open(filepath, 'r')
for line in fh:
line=line.rstrip('\n')
lines.append(line)
fh.close()
for line in lines:
print (line)
When you open file I think you have to specify how do you want to open it. In your example you should open it for reading like:
print open('text.txt',"r").read()
Hope this does the trick.

The best way to open two files

I need to open a file, read a line, hash it, and then save to a different file. Should I open both text files at the beginning of my script, or should I open each every time I save/read? I'm new to all this and I'm using python for android for sl4a. This is my code so far:
import android
import hashlib
import time
name = 0
droid = android.Android()
name = raw_input("Enter a password to hash: ")
hash_object = hashlib.md5 (name)
print(hash_object.hexdigest())
time.sleep(2)
print name
f = open('name.txt', 'w',)
f.write(hash_object.hexdigest())
f.close()
If you want to read from the file name.txt and write to another:
with open('name.txt', 'r') as f, open('out.txt', 'w') as f1:
line = f.next() # get first line
hash_object = hashlib.md5 (line)
f1.write(hash_object.hexdigest()) # write to second file
Yes should open both at the beginning and iterate through closing when you are done.
so instead of reading input from the user you want to read if from a file, say something like this:
import android
import hashlib
import time
name = 0
droid = android.Android()
with open('input.txt', 'r') as f_in, open('output.txt', 'w') as f_out:
for line in f_in.readlines():
hash_object = hashlib.md5 (line)
f_out.write(hash_object.hexdigest())

Replace and overwrite instead of appending

I have the following code:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
where I'd like to replace the old content that's in the file with the new content. However, when I execute my code, the file "test.xml" is appended, i.e. I have the old content follwed by the new "replaced" content. What can I do in order to delete the old stuff and only keep the new?
You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:
import re
myfile = "path/test.xml"
with open(myfile, "r+") as f:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
f.truncate()
The other way is to read the file then open it again with open(myfile, 'w'):
with open(myfile, "r") as f:
data = f.read()
with open(myfile, "w") as f:
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
Neither truncate nor open(..., 'w') will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4).
By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See http://man7.org/linux/man-pages/man2/truncate.2.html
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
Using truncate(), the solution could be
import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
#convert to string:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
f.truncate()
import os#must import this library
if os.path.exists('TwitterDB.csv'):
os.remove('TwitterDB.csv') #this deletes the file
else:
print("The file does not exist")#add this to prevent errors
I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
in my case the following code did the trick
with open("output.json", "w+") as outfile: #using w+ mode to create file if it not exists. and overwrite the existing content
json.dump(result_plot, outfile)
Using python3 pathlib library:
import re
from pathlib import Path
import shutil
shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
Similar method using different approach to backups:
from pathlib import Path
filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))

Categories

Resources