我想给怎么办阅读蟒蛇的例子。
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格式之间的映射。
曾经看过['struct'](http://docs.python.org/library/struct.html)模块? – Santa 2011-05-25 23:16:02
是的,但乍一看,我不知道如何指定像BinData这样的自定义结构。 – dj29 2011-05-25 23:23:10
你需要做什么,结构模块不能做什么? – Keith 2011-05-25 23:36:02