generate a hex file by converting strings into hex from a text file in Python

Viewed 567

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?

1 Answers

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