0

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?

Danijel
  • 8,198
  • 18
  • 69
  • 133
  • Does this answer your question? [Converting a float to bytearray](https://stackoverflow.com/questions/36893206/converting-a-float-to-bytearray) – Sören May 05 '22 at 09:40

1 Answers1

2

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.

Jan Christoph Terasa
  • 5,781
  • 24
  • 34