binary file reading in python

greg andruk meowing at banet.net
Wed Oct 6 21:57:33 EDT 1999


Daniel Weber <DWEBER1 at austin.rr.com> wrote:

> I've been mulling over a project to edit/view/search binary recipe files
> for a production tool multi-platform (OS/2, VMS, NT, linux) and was
> condidering using python.  However, the recipe files themselves are
> stored in binary format which I would have to read in and parse.  I"ve
> gone through my python books but have found no reference to reading in
> binary files or any functions to deal with fixed size binary data types
> like unsigned short, int and so on.  I know that I could write C code to
> interface to python but that would mitigate the advantage of writing it
> in python at all.  Are these type of read possible?

No problem.  See the docs for the built-in open() function in the
library reference; the 'b' flag will make sure you don't get CRLF
mangling, just like in C's fopen().

Then to get the data in, use the file object's read() method, which
works pretty much like its C counterpart; and Python's struct module
to convert the C data types into something Python can comfortably use.




More information about the Python-list mailing list