Pascal -> Python 'record' structures

Alex Martelli aleaxit at yahoo.com
Mon Dec 11 15:07:38 CET 2000


"deadmeat" <root@[127.0.0.1]> 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
> manually?

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.

    import struct

    format = "<dll"
    reclen = struct.calcsize(format)
    try:
        fileob = open("file.dat","rb")
        while 1:
            record = fileob.read(calcsize)
            if not record: break;
            myfloat, myint1, myint2 = struct.unpack(format, record)
            # now work with myfloat, myint1, myint2 ...
    finally:
        fileob.close()


Alex






More information about the Python-list mailing list