0
votes

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?

1
For your second question (please only ask one at a time!) you can – and should have – read the official documentation.Jongware
I'm removing the second question, because the alternative is to close this as too broad. Posts here should only contain a single question, and 'explain this code to me' without focusing on very specific statements or expressions is also too broad a subject here.Martijn Pieters
usr2564301 Thanks for letting me know, I will try to understand it from thereNewbie101

1 Answers

1
votes

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'