简体   繁体   中英

Python - How to edit hexadecimal file byte by byte

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?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM