简体   繁体   English

如何将不同类型的数据写入二进制文件

[英]How to write data of different types to binary file

From what I understand, I is an example of a format character which represents an unsigned integer and f is used to represent a float 据我了解, I是一个格式字符的示例,它表示无符号整数,而f用于表示浮点数

But when I try to write [120,3.5,255,0,100] to a binary file as bytes: 但是,当我尝试将[120,3.5,255,0,100]作为字节写入二进制文件时:

from struct import pack
int_and_float = [120,3.5,255,0,100]
with open ("bin_file.bin","wb") as f:
    f.write(pack("IfIII",*bytearray(int_and_float)))

Output 产量

TypeError: an integer is required TypeError:必须为整数

So is it not possible to store floats and integers as bytes in the same list? 因此,不可能将浮点数和整数作为字节存储在同一列表中吗?

Don't pass in a bytearray . 不要传入bytearray Pass in your values directly , as arguments: 直接将您的值作为参数传递:

f.write(pack("IfIII", *int_and_float))

It is the bytearray() call that throws the exception you see, and you don't even need this type here: bytearray()调用引发了您看到的异常,并且您甚至在这里都不需要这种类型:

>>> int_and_float = [120,3.5,255,0,100]
>>> bytearray(int_and_float)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

struct.pack() takes integers (and strings) and produces bytes as output: struct.pack()接受整数(和字符串)并产生字节作为输出:

>>> import struct
>>> struct.pack("IfIII", *int_and_float)
b'x\x00\x00\x00\x00\x00`@\xff\x00\x00\x00\x00\x00\x00\x00d\x00\x00\x00'

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

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