Reading 32 bit signed ieee 754 floating points from a binary file with python?

Razor Storm picture Razor Storm · Jun 9, 2011 · Viewed 21.4k times · Source

I have a binary file which is simple a list of signed 32 bit ieee754 floating point numbers. They are not separated by anything, and simply appear one after another until EOF.

How would I read from this file and interpret them correctly as floating point numbers?

I tried using read(4), but it automatically converts them to a string with ascii encoding.

I also tried using bytearray but that only takes it in 1 byte at a time instead of 4 bytes at a time as I need.

Answer

Marcelo Cantos picture Marcelo Cantos · Jun 9, 2011
struct.unpack('f', file.read(4))

You can also unpack several at once, which will be faster:

struct.unpack('f'*n, file.read(4*n))