在Python中读取结构二进制数据?

| 是否有诸如Ruby \ BinData之类的不错的Python解决方案来读取用户定义的二进制文件/流格式?如果不是,那么除了使用struct模块之外,在Python中首选的方法是什么? 我有一个二进制文件,用于存储事件的“记录”。记录的大小是动态的,因此我必须读取每个记录的前几个字节,以确定记录的长度和记录的类型。不同的记录类型将具有不同的字节布局。例如,类型为“ warning”的记录可能包含三个4字节的整数,后跟一个128字节的值,而类型为“ info”的记录可能仅具有五个4字节的整数。 以这样的方式定义不同的记录类型及其结构将是一件很不错的事,即我可以简单地将二进制blob传递给某些东西,然后处理其余的东西(对象生成等)。简而言之,您将定义有关如何解释二进制数据的模板/映射。     
已邀请:
也许您正在寻找Constructor,一个纯Python 2和3的二进制解析库?     
Python的struct模块的工作方式如下:
record_header = struct.Struct(\"<cb\") 
warning = struct.Struct(\"<iii128\")
info = struct.Struct(\"<iiiii\")

while True:
    header_text = input.read(record_header.size)
    # file is empty
    if not header_text:
       break
    packet_type, extra_data = record_header.unpack(header_text)
    if packet_type == \'w\':
        warning_data = warning.unpack( input.read(warning.size) )
    elif packet_type == \'i\':
        info_data = info.unpack( input.read(info.size) )
有关详细信息,请参见文档:http://docs.python.org/library/struct.html     
struct模块可能会起作用,但您也可以将python绑定用于Google的协议缓冲区。     
我想举一个例子,说明如何在python中阅读。
typedef struct {
    ID             chunkname;
    long           chunksize;

    /* Note: there may be additional fields here, depending upon your data. */

} Chunk;
您如何从python文件中读取此结构数据?这是一种方法:
class Chunk:
def __init__(self, file, align=True, bigendian=True, inclheader=False):
    import struct
    self.closed = False
    self.align = align      # whether to align to word (2-byte) boundaries
    if bigendian:
        strflag = \'>\'
    else:
        strflag = \'<\'
    self.file = file
    self.chunkname = file.read(4)
    if len(self.chunkname) < 4:
        # you need to take care of end of file
        raise EOFError
    try:
        # you could use unpack
        # http://docs.python.org/2/library/struct.html#format-characters
        # here \'L\' means \'unsigned long\' 4 standard size
        self.chunksize = struct.unpack(strflag+\'L\', file.read(4))[0]
    except struct.error:
        # you need to take care of end of file
        raise EOFError
    if inclheader:
        self.chunksize = self.chunksize - 8 # subtract header
    self.size_read = 0
    try:
        self.offset = self.file.tell()
    except (AttributeError, IOError):
        self.seekable = False
    else:
        self.seekable = True
因此,您需要了解c结构与struct.unpack()格式之间的映射 http://docs.python.org/2/library/struct.html#format-characters。     

要回复问题请先登录注册