pythonhex

Python: Read hex from file into list?


Is there a simple way to, in Python, read a file's hexadecimal data into a list, say hex?

So hex would be this:

hex = ['AA','CD','FF','0F']

I don't want to have to read into a string, then split. This is memory intensive for large files.


Solution

  • s = "Hello"
    hex_list = ["{:02x}".format(ord(c)) for c in s]
    

    Output

    ['48', '65', '6c', '6c', '6f']
    

    Just change s to open(filename).read() and you should be good.

    with open('/path/to/some/file', 'r') as fp:
        hex_list = ["{:02x}".format(ord(c)) for c in fp.read()]
    

    Or, if you do not want to keep the whole list in memory at once for large files.

    hex_list = ("{:02x}".format(ord(c)) for c in fp.read())
    

    and to get the values, keep calling

    next(hex_list)
    

    to get all the remaining values from the generator

    list(hex_list)