SelfishCosmonaut
SelfishCosmonaut

Reputation: 99

Convert bytes to readable strings in Python 3

I have a .bin file that holds data, however I am not sure of what format or encoding. I want to be able to transform the data into something readable. Formatting is not a problem, I can do that later.

My issue is parsing the file. I've tried to use struct, binascii and codecs with no such luck.

with open(sys.argv[1], 'rb') as f:
    data = f.read()
    lists = list(data)


    # Below returns that each item is class 'bytes' and a number that appears to be <255
    # However, if I add type(i) == bytes it spits an error
    for i in lists:
        print("Type: ", type(data))
        print(i, "\n")

    # Below returns that the class is 'bytes' and prints like this: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdd\x07\x00\x00\x0b\x00\x00\x00\x18\x00\x00\x00\x00\x00\x00\x00\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08@\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa0=\xa1D\xc0\x00\x00\x00\x00t\xdfe@
    # To my knowledge, this looks like hex notation. 
    print("Data type: ", type(data))
    print(data)

However, there should be someway to convert this into characters I can read i.e. letters or numbers, represented in a string. I seem to be over-complicating things, as I'm sure there's an inbuilt method that is being elusive.

Upvotes: 1

Views: 2363

Answers (1)

falsetru
falsetru

Reputation: 369414

Use binascii.hexlify:

>>> import binascii
>>> binascii.hexlify(b'\x00t\xdfe@')
b'0074df6540'

Upvotes: 1

Related Questions