user1675301
user1675301

Reputation: 41

How can I hex edit files in python2 byte by byte?

I am trying to make a python script that will edit the hex value of the file that I load and I got stuck. How can I hex edit a file byte by byte in python??

Upvotes: 4

Views: 2349

Answers (1)

nneonneo
nneonneo

Reputation: 179482

If the file is very large and you are doing only overwrite operations (no insertions or deletions), the mmap module allows you to treat a file as essentially a large mutable string. This allows you to edit the contents of the file byte-by-byte, or edit whole slices, without actually loading it all into memory (the mmap object will lazily load parts of the file into and out of memory as needed).

It's a bit cumbersome to use, but it is extremely powerful when needed.

Example:

$ xxd data
0000000: a15e a0fb 4455 1d0f b104 1506 0e88 08d6  .^..DU..........
0000010: 8795 d6da 790d aafe 9d6a 2ce5 f7c3 7c97  ....y....j,...|.
0000020: 4999 ab6b c728 352e b1fd 88e0 6acf 4e7d  I..k.(5.....j.N}
$ python
>>> import mmap
>>> f = open('data', 'a+')
>>> m = mmap.mmap(f.fileno(), 0)
>>> m[24:48]
'\x9dj,\xe5\xf7\xc3|\x97I\x99\xabk\xc7(5.\xb1\xfd\x88\xe0j\xcfN}'
>>> m[24:48] = 'a'*24
>>> m.close()
>>> f.close()
>>> ^D
$ xxd data
0000000: a15e a0fb 4455 1d0f b104 1506 0e88 08d6  .^..DU..........
0000010: 8795 d6da 790d aafe 6161 6161 6161 6161  ....y...aaaaaaaa
0000020: 6161 6161 6161 6161 6161 6161 6161 6161  aaaaaaaaaaaaaaaa

Upvotes: 7

Related Questions