Python how to make an executable from a text file - python

So what i want to do is write a .exe bynary to a .txt file and then write the .txt file to a .exe bynary, i tried this:
with open("old_File.exe", "rb") as f:
text_file = open("File.txt", "w")
byte = f.read(1)
while byte != "":
text_file.write(str(byte))
byte = f.read(1)
text_file.close()
with open("New_File.exe", "wb") as f:
text_file = open("File.txt", "r")
byte = text_file.read(12)
while byte != "":
print byte
f.write(byte)
byte = text_file.read(12)
text_file.close()
f.close()
but if i run the New_File.exe windows tels me it is not a valid aplication.
What am doing wrong?

The answer is:
The second time you were reading the *.txt file, you didn't open it in read binary mode, just in read, which is in fact, read text mode.
With older versions of Python it was platform dependent, i.e. this will be a problem only on Windows.
In Python 3, this will make you a problem on any platform.
Advice: Don't read a file in so small chunks if you don't have to, you will throttle poor Windows. Do it with at least 1024. It's often done with 4096 bytes. If the file is small, just do newfile.write(oldfile.read()) Todays PCs have enough RAM to put few MB in it without any problem.
And, there is no need for str(byte) as it is already a string.

To copy two files and preserve metadata, use shutil.copy2. This is a much safer way to copy files.

i foud the answer myself:
exe = open("exe.exe", "rb")
txt = open("txt.txt", "wb")
data = exe.read(100000)
while data != "":
txt.write(data)
data = exe.read(100000)
exe.close()
txt.close()
you actually have to write the binary on the text file instead of writing it as a string on the file itself.
#create new file
N_exe = open("N-exe.exe", "w+")
N_exe.close()
N_exe = open("N-exe.exe", "wb")
Txt = open("txt.txt", "rb")
data = Txt.read(100000)
while data != "":
N_exe.write(data)
data = Txt.read(100000)
N_exe.close()
Txt.close()

Related

How can I read a file in python?

Given some file that contain some text. How can I read Y bytes from this file after X bytes and print them?
I thought to use these functions: file = open("my_file", 'rb') and file.read(..) but I don't sure how to do it with these functions.
You almost have it, you are just missing seek to select the position to read from:
file = open("my_file", 'rb')
file.seek(X)
content = file.read(Y)
file.close()
print(content)
However, if an error happened, your file would be left open for longer than necessary, so almost always you should use the with syntax instead, which will automatically dispose of file at the end of the block:
with open("my_file", 'rb') as file:
file.seek(X)
content = file.read(Y)
print(content)
Note that content will be bytes, not text.

python encryption and decryption by using file

I am currently working on encrypting and decrypting files using python and I got to this part. I should replace original file with encryption dictionary and I tried to do so, but when I read the file and write it, it shows original text and encrypt version of it.
My original file contains the text, ABCDEF, and what I got for the result is ABCDEFGH!##$%^&*.
So I am not sure how to get rid of the original text.
Here is my code
import os
Dictionary = {'A':'!','B':'#','C':'#','D':'$','E':'%','F':'^'}
letterfile = input("What's the name of the file?")
exist = os.path.exists(letterfile)
if exist:
letterfile = open(letterfile, "r+")
readfile = letterfile.read()
for i in readfile:
if i in Dictionary:
letterfile.write(Dictionary[i])
letterfile.close()
You don't rewind to the beginning of the file when you write, so you're writing where the reading finished, which is the end of the file.
The right way to do this is to reopen the file for writing. That will empty the file and replace it with the encrypted version.
with open(letterfile, "r") as infile:
readfile = infile.read()
with open(letterfile, "w") as outfile:
for i in readfile:
letterfile.write(Dictionary.get(i, ""))
one way you can accomplish this by putting letterfile.truncate(0) after
readfile = letterfile.read() and before for i in readfile:
fully it would look like this
import os
Dictionary = {'A':'!','B':'#','C':'#','D':'$','E':'%','F':'^'}
letterfile = input("What's the name of the file?")
exist = os.path.exists(letterfile)
if exist:
letterfile = open(letterfile, "r+")
readfile = letterfile.read()
letterfile.truncate(0)
for i in readfile:
if i in Dictionary:
letterfile.write(Dictionary[i])
letterfile.close()

Converting a .csv.gz to .csv in Python 2.7

I have read the documentation and a few additional posts on SO and other various places, but I can't quite figure out this concept:
When you call csvFilename = gzip.open(filename, 'rb') then reader = csv.reader(open(csvFilename)), is that reader not a valid csv file?
I am trying to solve the problem outlined below, and am getting a coercing to Unicode: need string or buffer, GzipFile found error on line 41 and 7 (highlighted below), leading me to believe that the gzip.open and csv.reader do not work as I had previously thought.
Problem I am trying to solve
I am trying to take a results.csv.gz and convert it to a results.csv so that I can turn the results.csv into a python dictionary and then combine it with another python dictionary.
File 1:
alertFile = payload.get('results_file')
alertDataCSV = rh.dataToDict(alertFile) # LINE 41
alertDataTotal = rh.mergeTwoDicts(splunkParams, alertDataCSV)
Calls File 2:
import gzip
import csv
def dataToDict(filename):
csvFilename = gzip.open(filename, 'rb')
reader = csv.reader(open(csvFilename)) # LINE 7
alertData={}
for row in reader:
alertData[row[0]]=row[1:]
return alertData
def mergeTwoDicts(dictA, dictB):
dictC = dictA.copy()
dictC.update(dictB)
return dictC
*edit: also forgive my non-PEP style of naming in Python
gzip.open returns a file-like object (same as what plain open returns), not the name of the decompressed file. Simply pass the result directly to csv.reader and it will work (the csv.reader will receive the decompressed lines). csv does expect text though, so on Python 3 you need to open it to read as text (on Python 2 'rb' is fine, the module doesn't deal with encodings, but then, neither does the csv module). Simply change:
csvFilename = gzip.open(filename, 'rb')
reader = csv.reader(open(csvFilename))
to:
# Python 2
csvFile = gzip.open(filename, 'rb')
reader = csv.reader(csvFile) # No reopening involved
# Python 3
csvFile = gzip.open(filename, 'rt', newline='') # Open in text mode, not binary, no line ending translation
reader = csv.reader(csvFile) # No reopening involved
The following worked for me for python==3.7.9:
import gzip
my_filename = my_compressed_file.csv.gz
with gzip.open(my_filename, 'rt') as gz_file:
data = gz_file.read() # read decompressed data
with open(my_filename[:-3], 'wt') as out_file:
out_file.write(data) # write decompressed data
my_filename[:-3] is to get the actual filename so that it does get a random filename.

Python seemingly not reading from text file

files = []
with open("[...].log", "a+") as posshell:
for line in files:
print(line)
posshell_files.append(line)
I have no clue. It prints nothing. The array is empty. I've tried grabbing every null character and removing them in case it's UTF16 -> open as UTF8, didn't work.
You are passing the incorrect second argument to the open call to read the file in this way:
posshell_files = []
with open("posshell.log", "r") as posshell:
for line in posshell:
print(line)
posshell_files.append(line)
According to the Python docs for open, 'r' if the default flag for reading while 'a+' is for reading and writing but you will have to do so in a different manner:
with open("posshell.log","a+") as f:
f.seek(0)
print(f.read())
Try this
with open('posshell.log') as p:
content = p.readlines()
content = [x.strip() for x in content]

Confusing Error when Reading from a File in Python

I'm having a problem opening the names.txt file. I have checked that I am in the correct directory. Below is my code:
import os
print(os.getcwd())
def alpha_sort():
infile = open('names', 'r')
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
infile.close()
return 0
alpha_sort()
And the error I got:
FileNotFoundError: [Errno 2] No such file or directory: 'names'
Any ideas on what I'm doing wrong?
You mention in your question body that the file is "names.txt", however your code shows you trying to open a file called "names" (without the ".txt" extension). (Extensions are part of filenames.)
Try this instead:
infile = open('names.txt', 'r')
As a side note, make sure that when you open files you use universal mode, as windows and mac/unix have different representations of carriage returns (/r/n vs /n etc.). Universal mode gets python to handle this, so it's generally a good idea to use it whenever you need to read a file. (EDIT - should read: a text file, thanks cameron)
So the code would just look like this
infile = open( 'names.txt', 'rU' ) #capital U indicated to open the file in universal mode
This doesn't solve that issue, but you might consider using with when opening files:
with open('names', 'r') as infile:
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
return 0
This closes the file for you and handles exceptions as well.

Categories

Resources