Python读取二进制文件

Fri 20 February 2009
  • 手艺 tags:
  • c
  • python published: true comments: true

Python里虽然可以通过'b'的标记来区别普通文件和二进制文件,但是依然是把二进制文件当作普通文本处理。要读写二进制文件,需要用struct库来作pack和unpack。

比如我最近拿到一个如下数据结构的二进制文件

[codesyntax lang="c" lines="fancy"]
struct DEMTYPE {
int row;
int col;
float xmin;
float ymin;
float xmax;
float ymax;
float size;
float vmin;
float vmax;
float scale;
float *data;
};
[/codesyntax]

其中data是一个长度为row*col的数组。要读取这样一个二进制文件,可以用这样的代码
[codesyntax lang="python" lines="fancy"]
row, col, xmin, ymin, xmax, ymax, size, vmin, vmax, scale = \
struct.unpack('<2i8f', datastring[:(4*2+4*8)])
vdata = struct.unpack('<'+str(row*col)+'f', datastring[(4*2+4*8):])
[/codesyntax]
核心是unpack的第一个参数,用来标识二进制数据的格式,其中<表示little-endian,i表示整型数,f表示单精度浮点数,数字是量词。

更详细的说明可以看manual: http://docs.python.org/library/struct.html

好吧,我承认我写这个是来测试highlight插件的。