我正在将二进制文件读入列表并解析二进制数据。我使用 unpack() 将数据的某些部分提取为原始数据类型,并且我想编辑该数据并将其插入到原始字节列表中。使用pack_into()会很容易,除了我使用的是Python 2.4,并且 pack_into() 直到 2.5 才引入
有谁知道以这种方式序列化数据的好方法,以便我可以完成与 pack_into() 基本相同的功能?
最佳答案
你看过bitstring
吗?模块?它的设计目的是使二进制数据的构造、解析和修改比直接使用 struct
和 array
模块更容易。
它是专门为在位级别工作而设计的,但也可以在字节级别上工作。它还适用于 Python 2.4。
from bitstring import BitString
s = BitString(filename='somefile')
# replace byte range with new values
# The step of '8' signifies byte rather than bit indicies.
s[10:15:8] = '0x001122'
# Search and replace byte value with two bytes
s.replace('0xcc', '0xddee', bytealigned=True)
# Different interpretations of the data are available through properties
if s[5:7:8].int > 1000:
s[5:7:8] = 1000
# Use the bytes property to get back to a Python string
open('newfile', 'wb').write(s.bytes)
存储在BitString
中的底层数据只是一个数组
对象,但具有一套全面的函数和特殊方法,使其易于修改和解释。
关于python - 操作字节列表时使用 pack_into() 的替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1133044/