Python读取二进制文件

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插件的。

This entry was written by Sunng , posted on Friday February 20 2009at 06:02 pm , filed under 手艺 and tagged , . Bookmark the permalink . Post a comment below or leave a trackback: Trackback URL.

2 Responses to “Python读取二进制文件”

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word