Pascal -> Python 'record' structures
aleaxit at yahoo.com
Mon Dec 11 15:07:38 CET 2000
"deadmeat" <email@example.com> wrote in message
news:2y4Z5.7634$KY1.20696 at news1.rivrw1.nsw.optushome.com.au...
> Can anyone tell me how to read in file records that were created by Pascal
> and C programs? Will I have to write a wrapper and parse the raw data
The python 'struct' module handles the task of converting such
binary 'struct'/'record' data to Python thingies. You do have
to open the file for reading in binary mode and read the right
number of bytes at a time, but then struct will nicely unpack
them for you.
Suppose for example that the file is made up of records each
of which is a (binary little-endian) IEEE-double precision
(64-bit) number followed by two signed 4-byte integers.
format = "<dll"
reclen = struct.calcsize(format)
fileob = open("file.dat","rb")
record = fileob.read(calcsize)
if not record: break;
myfloat, myint1, myint2 = struct.unpack(format, record)
# now work with myfloat, myint1, myint2 ...
More information about the Python-list