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())
Related
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.
I was wondering if there is anyway that from a filename provided by an user we can get the body of the file
Here as sample of my code
fname = input('Enter filename...')
fileObject = open(fname, 'r')
print(fname)
Yes, you need to read the data from the file and then print it out, or do everything at once:
fname = input("What's the file name? ")
# this assumes it's on the same directory
with open(fname, 'r') as file:
print(file.read())
You can try this: (read the official Python doc. too)
with open(filename) as f:
content = f.read()
# you may also want to remove whitespace characters like `\n` at the end of each line
print(content)
I want to output csv file with python. I have gone through below code and it is working well with .txt file but I am unable to print csv through it.
import os
import tempfile
filename = tempfile.mktemp(".txt")
open (filename , "w").write ("Printing file")
os.startfile(filename, "print")
Actually I want to print a csv file that had been already created, there will be no need to write and create new file then print it out.
Edit: From print I meant hardcopy print through printer
If you want to print the content of a csv you can try this:
import csv
file_path = 'a.csv'
with open(file_path) as file:
content = csv.reader(file)
for row in content:
print(row)
I was talking about printing csv file as hardcopy with python code.
def printing():
#reading from csv writing in txt
with open("CSV_files//newfile.txt", "w") as my_output_file:
cs = pd.read_csv("CSV_files\\attendance.csv",header=None,index_col=None)
with open("CSV_files//attendance.csv", "r") as my_input_file:
[ my_output_file.write(" | ".join(row)+'\n') for row in csv.reader(my_input_file)]
my_output_file.close()
#reading from file and storing into reader and converting into string as .write() takes string
strnew = ""
with open('CSV_files//newfile.txt',"r") as f:
reader = f.read()
strnew = reader
#for checking
with open('CSV_files//print.txt',"w") as f:
f.write(strnew)
#printing
filename = tempfile.mktemp("attendance.txt")#creating a temp file
open (filename , "w").write(strnew)
os.startfile(filename, "print")
messagebox.showinfo("Print","Printing Request sent successfully!")
For more info:
github project link
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.
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))