4

我正在尝试制作一个 python 脚本来编辑我加载的文件的十六进制值,但我被卡住了。如何在 python 中逐字节十六进制编辑文件?

4

1 回答 1

7

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
于 2012-09-16T07:24:55.093 回答