Reading a Delphi binary in Python

I have a file 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 parse data in files (many MB in size) using Python, if possible - is there an easy way to read data and pass data to Python objects that are similar in form to a Delphi record? Maybe someone knows about this library?

This is compiled on Delphi 7 with the following parameters that may (or may not) be appropriate,

  • Alignment of fields of record: 8
  • Pentium Safe FDIV: False
  • Stack Frames: False
  • Optimization: True
+6
python file-io delphi
source share
3 answers

Here are complete solutions thanks to tips 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:] 
+5
source share

I do not know how Delphi stores data internally, but if it is simple byte data (therefore not serialized and garbled), use struct . This way you can process the string from the python file as binary data. Also, open files as binary file(open,'rb') .

+2
source share

Please note that when you define an entry in Delphi (for example, struct in C), the fields are laid out in order and in binary format, taking into account the current alignment (for example, bytes are aligned by 1 byte boundaries, words by 2 bytes, integers by 4 bytes, etc., but it may vary depending on the compiler settings.

When serializing to a file, you probably mean that this record is written in binary form to a file, and the next record is written after the first, starting from the position of sizeof (structure), etc. etc. Delphi does not indicate how it should be serialized to / from a file, so the information you give leaves us with fortune-telling.

If you want to make sure that this is always the same without the intervention of any compiler settings, use a packed entry.

A real one can have several values ​​(this is a 48-bit float type for older versions of Delphi, and then a 64-bit float (IEEE double)).

If you can’t access the Delphi code or compile it yourself, just check the data using the HEX editor, you should clearly see the boundaries of the records, since they start with integers and only floats follow.

+2
source share

All Articles