Question

I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tutorials/guides?

Was it helpful?

Solution

Python standard library has mmap module, which can be used to do exactly this. Take a look on the documentation for further information.

OTHER TIPS

Depending on what you want to do it might be enough to open the file in binary mode and read the data with the normal file functions:

# load it
with open("somefile", 'rb') as f:
    data = f.read()

# do something with data
data.reverse()

# save it
with open("somefile.new", 'wb') as f:
    f.write(data)

Python doesn't really care if the data string contains "binary" or "text" data. If you just want to do simple modifications to a file of reasonable size this is probably good enough.

The Hachoir framework is a set of Python library and tools to parse and edit binary files:

http://pypi.python.org/pypi/hachoir-core

It has knowledge of common file types, so this could just be what you need.

Check out the stuct module.

This module performs conversions between Python values and C structs represented as Python strings. It uses format strings (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. This can be used in handling binary data stored in files or from network connections, among other sources.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top