'Python: how to write a 32-bit float number into a file?

This code gives:
TypeError: a bytes-like object is required, not 'float'

if __name__ == '__main__':
    f32_number = float(1)
    with open("test.f32", "wb") as f:
        f.write(f32_number)

How do I write a float 32-bit number into a binary file?



Solution 1:[1]

Convert the number to bytes using struct:

import struct

if __name__ == '__main__':
    f32_number = float(1)
    with open("test.f32", "wb") as f:
        b = struct.pack('f', f32_number)
        f.write(b)

If you want to share files between platforms, be wary of endianness. It will be better to explicitly use > or < in that case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jan Christoph Terasa