是否有像Ruby的BinData这样的Python解决方案用于读取用户定义的二进制文件/流格式?如果没有,那么除了使用struct模块之外,Python中首选的方法是什么?
我有一个存储事件“记录”的二进制文件。记录的大小是动态的,因此我必须读取每条记录的前几个字节以确定记录长度和记录类型。不同的记录类型将具有不同的字节布局。例如,类型为“warning”的记录可能包含三个4字节的整数,后跟一个128字节的值,而“info”类型的记录可能只包含五个4字节的整数。
以这样的方式定义不同的记录类型及其结构会很好,我可以简单地将二进制blob传递给某个东西,然后处理其余的(对象生成等)。简而言之,您定义了关于如何解释二进制数据的模板/地图。
答案 0 :(得分:3)
也许你正在寻找Construct,一个纯Python 2& 3二进制解析库?
答案 1 :(得分: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
答案 2 :(得分:2)
struct模块可能会起作用,但你也可以使用python绑定到Google的protocol buffers。
答案 3 :(得分:-1)
我想举一个如何在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。