简体   繁体   English

如何以字节为单位对python2中的文件进行十六进制编辑?

[英]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. 我正在尝试创建一个python脚本,它将编辑我加载的文件的十六进制值,然后卡住了。 How can I hex edit a file byte by byte in python?? 如何在python中逐字节十六进制编辑文件?

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. 如果文件非常大并且您只进行覆盖操作(无插入或删除),则mmap模块允许您将文件视为一个大型可变字符串。 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). 这允许您逐个字节地编辑文件的内容,或编辑整个切片,而无需将其全部加载到内存中( mmap对象将根据需要懒惰地将文件的一部分加载到内存中和内存中)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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