MercilessMaverick
MercilessMaverick

Reputation: 257

How to write hex to file in python

I really don't understand what is going on with Python.

If I use

f.write(data.encode("hex"))

Python converts my data into a hex string, so in the case of "hello" I get the string 68656c6c6f.

However using

f = open('file.dat', 'wb')
f.write("hello".encode("hex"))
f.close()

Will just write the ascii of the hex. The same is true of hexlify. I need the hex in the \00 format, yet everything seems to want to give me hex strings in ascsii

Upvotes: 3

Views: 2515

Answers (2)

Vahid Rafiei
Vahid Rafiei

Reputation: 382

If you are using Python 3.x, we have a lib called binascii for Converting between binary and ASCII...

>>> import binascii
>>> binascii.hexlify(b'Hi')

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113958

>>> "\\"+"\\".join(["hello".encode("hex")[i:i+2] for i in range(0,len("hello".encode("hex")),2)])
'\\68\\65\\6c\\6c\\6f'

there now you have \ prepended to every 2 chars of hex

Upvotes: 1

Related Questions