简体   繁体   English

Python:如何将32位浮点数写入文件?

[英]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?如何将 32 位浮点数写入二进制文件?

Convert the number to bytes using struct :使用struct将数字转换为bytes

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.在这种情况下,明确使用><会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM