Question

I have list with 8 bit numbers like [255, 8, 16, 254 ...] count of these files about 8000. I have question about saving these numbers, when i save it, it must be 8000 byte, am I false ? But I have about 20kb. How can I save this numbers as 8 bit when I read it I want to read as byte.

file = open(name,"wb")
for el in data:
    file.write(bytes(el))

where is my mistake ? please help

Was it helpful?

Solution

The answer depends heavily on what Python version you are using.

If it is Python 3, you are calling bytes() incorrectly; by giving it an integer, you are asking for a bytes() object of that size:

>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

That's 10 null bytes, not one byte with the value 0x10.

Pass in a sequence instead:

>>> bytes([10])
b'\n'

In fact, you don't need your loop at all; if data is all integers, you can create your bytes object in one go and write that:

with open(name,"wb") as f:
    file.write(bytes(data))

If this is Python 2, you should not be using bytes() at all, it's just an alias for str():

>>> bytes(10)
'10'

That's the characters 1 and 0 (ASCII codepoints 49 and 48), not a byte with value 0x10.

You can use bytearray() the same way you could use bytes() (and bytearray()) in Python 3; create one such object from data and write that:

with open(name,"wb") as f:
    file.write(bytearray(data))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top