Reputation: 8600
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?
Upvotes: 0
Views: 493
Reputation: 5935
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.
Upvotes: 2