简体   繁体   中英

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

But when I try to write [120,3.5,255,0,100] to a binary file as bytes:

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

So is it not possible to store floats and integers as bytes in the same list?

Don't pass in a 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:

>>> 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:

>>> 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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