34

How would I convert a file to a HEX string using Python? I have searched all over Google for this, but can't seem to find anything useful.

1 Answer 1

69
import binascii
filename = 'test.dat'
with open(filename, 'rb') as f:
    content = f.read()
print(binascii.hexlify(content))
Sign up to request clarification or add additional context in comments.

5 Comments

will this convert png, jpg and other image format files?
Yes, it opens the specified file of any type in binary format and the function just converts binary to hex format.
the hexdump prints the lines like "0000000 2123 7472 7070 616c 3179" where as the above code prints like "2321727470706c6179". Doe you see the bytes? they are flipped. 2123 is printed as 2321. Same 7472 as 7274. Why is so?
@BTRNaidu: Your machine uses litte endian order: "This is the way a hexdump is displayed: because the dumping program is unable to know what kind of data it is dumping, the only orientation it can observe is monotonically increasing addresses. The human reader, however, who knows that he or she is reading a hexdump of a little-endian system ... reads the byte sequence 0Dh,0Ch,0Bh,0Ah as the 32-bit binary value 168496141, or 0x0a0b0c0d in hexadecimal notation."
On Ubuntu you can check your machine's endianness by running lscpu. To get hexdump output to match the output of the code above, run hexdump -C /path/to/file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.