Good afternoon, friends, I just started learning python, I found this code that suits my needs, but on the way out everything is synchronized in one line, help me with this problem.
"
import ecdsa
import hashlib
import base58
with open("my_private_key.txt", "r") as f: #Input file path
for line in f:
#Convert hex private key to bytes
private_key = bytes.fromhex(line)
#Derivation of the private key
signing_key = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()
public_key = bytes.fromhex("04") + verifying_key.to_string()
#Hashes of public key
sha256_1 = hashlib.sha256(public_key)
ripemd160 = hashlib.new("ripemd160")
ripemd160.update(sha256_1.digest())
#Adding prefix to identify Network
hashed_public_key = bytes.fromhex("00") + ripemd160.digest()
#Checksum calculation
checksum_full = hashlib.sha256(hashlib.sha256(hashed_public_key).digest()).digest()
checksum = checksum_full[:4]
#Adding checksum to hashpubkey
bin_addr = hashed_public_key + checksum
#Encoding to address
address = str(base58.b58encode(bin_addr))
final_address = address[2:-1]
print(final_address)
with open("my_addresses.txt", "a") as i:
i.write(final_address)
"
print writes a trailing newline after writing all its arguments. write does not; you have to supply it yourself.
with open("my_addresses.txt", "a") as i:
i.write(final_address + "\n")
Or, you can use print:
with open("my_addresses.txt", "a") as i:
print(final_address, file=i)
Ignoring many of its keyword arguments, print is defined something like
def print(*args, end='\n', sep=' ', file=sys.stdout):
file.write(sep.join(args))
file.write(end)
Also, note that you don't need to repeatedly open your output file. You can open it at the same time as the input and leave it open for the duration of the loop.
with open("my_private_key.txt", "r") as f, \
open("my_addresses.txt", "a") as i:
for line in f:
...
print(final_address, file=i)
Related
I have peiced together some code from the internet to capture pressed keys and the current active window title and am trying to write the output of the python script to a text file.
The script works fine in the IDLE console and prints pressed keys and logs any change in the current active window.
from pynput.keyboard import Key, Listener
import time
from win32gui import GetWindowText, GetForegroundWindow
import datetime
from threading import Thread
def on_press(key):
print ('{0} pressed'.format(key))
def on_release(key):
('{0} release'.format(key))
if key == Key.esc:
return False
def get_titles():
current_title = None
while True:
moment2 = datetime.datetime.now().strftime("%d-%b-%Y [ %H:%M:%S ]")
new_title = GetWindowText(GetForegroundWindow())
if new_title != current_title:
if len(new_title) > 0:
#logging.info(" Moved to : " + new_title)
current_title = new_title
time.sleep(0.1)
#print(new_title)
ff= (moment2 + " : " + "Moved T0 : "+ new_title)
print (ff)
I am looking for a simple way to write the outputs i can see in the console to a text file. It is probably very simple but i am very much a beginner. Thanks
Python has a native open() function, no import needed, which allows you to handle files. This function "loads" the file into memory, and can be set into various modes:
open("filename.txt", "a"), appending the content to a new line;
open("filename.txt", "w"), overwriting the content; and
open("filename.txt", "r"), setting it to read-only.
open("filename.txt", "x"), to create a file.
You can add a "+" to each of this modes ("a+", "w+"), if you want the file to be created if it doesn't already exist.
You define the file in memory to a variable as such: a = open("filename.txt", "w"), and can then text = a.read() to load the content of the file to a string, or a.readlines() to load the strings into an array, split per \n.
Use a.write("Your desired output") to save the content to the file, if the file is in write or append modus.
Edit:
Try to only open files for as long as they are actually needed.
with open("filename.txt", "r") as f:
file_contents = f.read()
# file_contents = "This file contains\nvery important information"
file_lines = f.readlines()
# file_lines = ["This file contains", "very important information"]
# Similar to file_lines = file_contents.split("\n")
in order to avoid blocking other parts of your program, and avoid corrupting your files if Python crashes unexpectedly.
Just add
with open('textfile.txt', 'a+') as f:
f.write(ff)
a option is for appending to a file and + means that if the file is not there just create one with the specified name.
EDIT:
def on_press(key):
print ('{0} pressed'.format(key))
with open('textfile.txt', 'a+') as f:
f.write(ff)
EDIT 2:
def on_press(key):
print ('{0} pressed'.format(key))
k = key + '\n'
with open('textfile.txt', 'a+') as f:
f.write(key)
# and in get_titles()
ff= (moment2 + " : " + "Moved T0 : "+ new_title + '\n')
with open('textfile.txt', 'a+') as f:
f.write(ff)
try this when run program in console
python your_script.py > path_to_output_file/outpot.txt
in case '>' not work then try '>>'
I have text that is key-value pairs separated by '='. I would like to replace the line if the key matches. if not, i would like to append it at the bottom. I've tried several ways, including:
def split_command_key_and_value(command):
if '=' in command:
command2 = command.split('=')
return command2
def test(command, path):
command2 = split_command_key_and_value(command)
pattern = command2[0]
myfile = open(path,'r') # open file handle for read
# use r'', you don't need to replace '\' with '/'
result = open(path, 'w') # open file handle for write
for line in myfile:
line = line.strip() # it's always a good behave to strip what you read from files
if pattern in line:
line = command # if match, replace line
result.write(line) # write every line
myfile.close() # don't forget to close file handle
result.close()
I know the above is just to replace text, but it deletes the text in the file, and I can't see why. Could someone point me in the right direction?
Thanks
Update:
I'm almost there, but some of my lines have similar keys, so mutiple lines are matching when only 1 should. I've tried to incorporate a regex boundary in my loop with no luck. My code is below. Does anyone have a suggestion?
There is some text in the file that isn't key-value, so I would like to skip that.
def modify(self, name, value):
comb = name + ' ' + '=' + ' ' + value + '\n'
with open('/file/', 'w') as tmpstream:
with open('/file/', 'r') as stream:
for line in stream:
if setting_name in line:
tmpstream.write(comb)
else:
tmpstream.write(line)
I think I got it. See code below.
def modify(self, name, value):
comb = name + ' ' + '=' + ' ' + value + '\n'
mylist = []
with open('/file/', 'w') as tmpstream:
with open('/file/', 'r') as stream:
for line in stream:
a = line.split()
b = re.compile('\\b'+name+'\\b')
if len(a) > 0:
if b.search(a[0]):
tmpstream.write(comb)
else:
tmpstream.write(line)
I spoke too soon. It stops at the key-value I provide. So, it only writes one line, and doesn't write the lines that don't match.
def modify(name, value):
comb = name + ' ' + '=' + ' ' + value + '\n'
mylist = []
with open('/file1', 'w') as tmpstream:
with open('/file2', 'r') as stream:
for line in stream:
a = line.split()
b = re.compile('\\b'+name+'\\b')
if len(a) > 0:
if b.search(a[0]):
tmpstream.write(comb)
else:
tmpstream.write(line)
Can anyone see the issue?
Because when you open file for writing
result = open(path, 'w') # open file handle for write
you just erase it content. Try to write in different file and after all work done replace old file with new one. Or read all data into memory and then process it and write to file.
with open(path) as f:
data = f.read()
with open(path, 'w') as f:
for l in data:
# make job here
first of all you are reading an writing the same file ...
you could first read it all and the write line by line
with open(path,'r') as f:
myfile = f.read() # read everything in the variable "myfile"
result = open(path, 'w') # open file handle for write
for line in myfile.splitlines(): # process the original file content 1 line at a time
# as before
I strongly recommend reading python's documentation on how to read and write files.
If you open an existing file in write-mode open(path, 'w'), its content will be erased:
mode can be (...) 'w' for only writing (an existing file with the same name will be erased)
To replace a line in python you can have a look at this: Search and replace a line in a file in Python
Here is one the solutions provided there adapted to your context (tested for python3):
from tempfile import mkstemp
from shutil import move
from os import close
def test(filepath, command):
# Split command into key/value
key, _ = command.split('=')
matched_key = False
# Create a temporary file
fh, tmp_absolute_path = mkstemp()
with open(tmp_absolute_path, 'w') as tmp_stream:
with open(filepath, 'r') as stream:
for line in stream:
if key in line:
matched_key = True
tmp_stream.write(command + '\n')
else:
tmp_stream.write(line)
if not matched_key:
tmp_stream.write(command + '\n')
close(fh)
move(tmp_absolute_path, filepath)
Note that with the code above every line that matches key (key=blob or blob=key) will be replaced.
Hey guys i have started doing some python coding and i was able to create this program that decrypts the encrypted text i provide with the use of the key i provide can someone help me change this decryption of text into decryption of files.
import sys
def decrypt(cipher, key):
plain = ""
for index in range(len(cipher)):
if cipher[index].isalpha():
if cipher[index].isupper():
plain = plain + chr((ord(cipher[index]) - 64 - key) % 26 + 64)
elif cipher[index].islower():
plain = plain + chr((ord(cipher[index]) - 96 - key) % 26 + 96)
else:
plain = plain + cipher[index]
return plain
in_filename = sys.argv[1]
key = int(sys.argv[2])
out_filename = sys.argv[3]
with open(in_filename, "r") as f:
encrypted = f.read()
decrypted = decrypt(encrypted, key)
with open(out_filename, "w+") as f:
f.write(decrypted)
cipher = sys.argv[1]
plain = sys.argv[1]
key = int(sys.argv[2])
print('{}'.format(cipher))
print('{}'.format(decrypt(cipher, key)))
i can use my current program by typing in this command in the terminal
python cipher.py 'Yaholy' 7 which decrypts this word into Rather
You can use what you already have, and just read from a file and then write the result back out.
in_filename = sys.argv[1]
key = int(sys.argv[2])
out_filename = sys.argv[3] # if you want
with open(in_filename, "r") as f:
encrypted = f.read()
decrypted = decrypt(encrypted, key)
with open(out_filename, "w+") as f:
f.write(decrypted)
print(decrypted) # if you don't want to save to a file
Then you can call it with, for example, python cipher.py encrypted.txt 7 decrypted.txt.
I am trying to create a file with encrypted username, password and computer name when the user logs in. And the same data I want to use again to authenticate the data but by decrypting them first. I am trying to use something that is built in python and simple.
import os
import bz2
os.chdir("D:/test")
encrypted_username = bz2.compress('username')
encrypted_password = bz2.compress('password')
computer_name = os.environ['COMPUTERNAME']
encrypted_computer_name = bz2.compress(computer_name)
f = open("Session.dat", "w")
f.write(encrypted_username + '\n')
f.write(encrypted_password + '\n')
f.write(encrypted_computer_name)
f.close()
f = open("Session.dat", "r")
data = f.read()
d_data = bz2.decompress(data)
f.close()
print(d_data)
But when I decrypt the data in the file and print it. I get the answer as below. Why am I not getting the password and computer name?? Thank you.
username
The code compressed the strings separately. You should read all lines and decompress them line by line as alecxe commented. But that is not practical because compressed data could contians newline(s).
Instead combine strings (In the following code, I used NULL byte \0 as separator), then compress the combined string.
Decompress: After decompress, split combined strings using the same separator.
import os
import bz2
#os.chdir("D:/test")
username = 'username'
password = 'password'
computer_name = os.environ['COMPUTERNAME']
compressed = bz2.compress(username + '\0' + password + '\0' + computer_name)
with open("Session.dat", "wb") as f:
f.write(compressed)
with open("Session.dat", "rb") as f:
d_data = bz2.decompress(f.read())
print(d_data.split('\0'))
BTW, you should use binary mode to read/write compressed data.
This program is a basic encoder in python and I want to see if I can make it more efficient without changing the names of the defined variables. Can someone give me some suggestions?
def encode(pattern, filename):
f = open(filename, "rt")
contents = f.read()
f.close()
printNow(contents)
changes = pattern.split("|")
for str in changes:
printNow("Change "+ str[0] + " to " + str[1])
newMsg = ""
for char in contents:
for change in changes:
if char == change [0]:
char = change[1]
newMsg += char
f = open(filename + "encoded", "wt")
f.write(newMsg)
f.close()
f = open(filename + "encoded", "rt")
printNow(f.read())
f.close()
encode("ae|ga|s3", "C:\\Users\\Shaun\\Desktop\\Test.txt")
import string
def encode(pattern, filename):
with open(filename) as f:
contents = f.read()
s = string.maketrans(*[''.join(a) for a in zip(*pattern.split('|'))])
newMsg = contents.translate(s)
with open(filename + 'encoded', 'rt') as f:
f.write(newMsg)
Use str.translate() instead of doing all the replacements the hard way, and do it line-by-line.
First of all you need to consider the option that your algorithm is already good enough. Even if it can be optimized, if your code is part of a bigger program and it only executes during 0.1% of time, for instance, then it will be most probably useless to optimize the code, since the rest of the program will dominate the total execution time.
If you really have a problem in your code, then I would start by analyzing the complexity of your algorithm.
And finally, you could try to find some bottlenecks in your code. For that, I would profile the code with something like python's timeit.
The str.translate() method works well for character substitutions, but here's another fast way I've used that also works for multi-character substitutions:
import re
def encode(pattern, filename):
f = open(filename, "rt")
contents = f.read()
f.close()
printNow(contents)
change_dict = {}
matches = []
changes = pattern.split("|")
for str in changes:
printNow("Change "+ str[0] + " to " + str[1])
change_dict[str[0]] = str[1]
matches.append(str[0])
change_re = re.compile("|".join(re.escape(x) for x in matches))
newMsg = change_re.sub(lambda m: change_dict[m.group(0)], contents)
f = open(filename + "encoded", "wt")
f.write(newMsg)
f.close()
f = open(filename + "encoded", "rt")
printNow(f.read())
f.close()
encode("ae|ga|s3", "C:\\Users\\Shaun\\Desktop\\Test.txt")