[英]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.