[英]How to write data of different types to binary file
据我了解, I
是一个格式字符的示例,它表示无符号整数,而f
用于表示浮点数
但是,当我尝试将[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)))
产量
TypeError:必须为整数
因此,不可能将浮点数和整数作为字节存储在同一列表中吗?
不要传入bytearray
。 直接将您的值作为参数传递:
f.write(pack("IfIII", *int_and_float))
是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()
接受整数(和字符串)并产生字节作为输出:
>>> 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.