Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a Delphi binary file in Python

I have a file that was written with the following Delphi declaration ...


Type
  Tfulldata = Record
    dpoints, dloops : integer;
    dtime, bT, sT, hI, LI : real;
    tm : real;
    data : array[1..armax] Of Real;
  End;

...
Var:
  fh: File Of Tfulldata;

I want to analyse the data in the files (many MB in size) using Python if possible - is there an easy way to read in the data and cast the data into Python objects similar in form to the Delphi records? Does anyone know of a library perhaps that does this?

This is compiled on Delphi 7 with the following options which may (or may not) be pertinent,

  • Record Field Alignment: 8
  • Pentium Safe FDIV: False
  • Stack Frames: False
  • Optimization: True
like image 677
Brendan Avatar asked Apr 23 '10 16:04

Brendan


2 Answers

Here is the full solutions thanks to hints from KillianDS and Ritsaert Hornstra

import struct
fh = open('my_file.dat', 'rb')
s = fh.read(40256)
vals = struct.unpack('iidddddd5025d', s)
dpoints, dloops, dtime, bT, sT, hI, LI, tm = vals[:8]
data = vals[8:]
like image 125
Brendan Avatar answered Sep 19 '22 12:09

Brendan


I do not know how Delphi internally stores data, but if it is as simple byte-wise data (so not serialized and mangled), use struct. This way you can treat a string from a python file as binary data. Also, open files as binary file(open,'rb').

like image 37
KillianDS Avatar answered Sep 21 '22 12:09

KillianDS