nuvolet
nuvolet

Reputation: 39

Reading binary files using python

I have some binary files which have header that I am interested to read. These binary Fortran files have this structure:

TYPE File_syn
    Sequence
    Character (Len=64) :: Site_ID                   !   64 bytes   64 
    Character (Len=4)  :: year                      !    4 bytes   68
    Character (Len=4)  :: mon                       !    4 bytes   72
    Real    :: lat                                  !    4 bytes   76
    Real    :: lon                                  !    4 bytes   80
    Real    :: elev                                 !    4 bytes   84
    Real    :: extras                               !    4 bytes   88
    Character (Len=32), Dimension(50) :: label      ! 1600 bytes 1688
    Character (Len=2408) :: padding                 ! 2408 bytes 4096
END TYPE File_syn

I am interested to read these files using Python and overall get the variable extra and label and this last one convert those bytes into an array character.

I tried something like this:

 with open(file_path, 'rb') as f:
    Site_ID = f.read(64)
    year = f.read(4)
    month = f.read(4)
    lat = f.read(4)
    lon = f.read(4)
    elev = f.read(4)
    extras = f.read(4)
    label = f.read(1600)
    header_file = f.read(2408)

print(extras)
print(label)

For extras I have something like this:

b'A0\x00\x00'

How could I convert to characters?

Thanks in advance

Upvotes: 0

Views: 533

Answers (1)

patate1684
patate1684

Reputation: 649

You can use struct module to convert binary string into float.

For example :

import struct
x = struct.unpack('f', b'A0\x00\x00')[0]

Give 1.7310239929804465e-41 as output

It's probably not the most elegant solution because you have to convert 'extras' to string.

x = struct.unpack('f', str(extras))[0]

Upvotes: 1

Related Questions