How to read last float number of binary file in Python in a fast way

Viewed 24

I have a binary file, that stores all float numbers. I would like to get the final number in that file in Python.

What's the fastest way?

1 Answers

Assuming the file is just tightly packed floats,

import struct

s = struct.Struct("<f")  # single little-endian float

with open("binary-blob.dat", "rb") as f:
   f.seek(-s.size, 2)  # seek to the end of the file minus the size of the float
   buf = f.read(s.size)  # read the float
   last_float, = s.unpack(buf)  # unpack the float

You can change the struct specifier depending on the endianness and width of your floats.

Related