Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a list of integers to a binary file in python

I have a list of integers which represent bytes of code. How can I write them to a binary file fast and more efficiently.

I have tried:

with open (output1, "wb") as compdata:
    for row in range(height):
        for data in cobs(delta_rows[row].getByte_List()):
            output_stream.append(Bits(uint=data, length=8))
    compdata.write(output_stream.tobytes())

and

with open (output1, "wb") as compdata:
    for row in range(height):
        bytelist = cobs(delta_rows[row].getByte_List())
        for byte in bytelist:
            compdata.write(chr(byte))

both get me a result which I think is correct (I have yet to reverse the process) but both take a long time (6min and 4min respectfully).

like image 935
Marmstrong Avatar asked Dec 22 '25 05:12

Marmstrong


1 Answers

Use a bytearray() object, write that straight to the output file:

with open (output1, "wb") as compdata:
    for row in range(height):
        bytes = bytearray(cobs(delta_rows[row].getByte_List()))
        compdata.write(bytes)

A sequence of integers is interpreted by a bytearray() as a sequence of byte values.

In Python 3, you can use a bytes() type as well, with the same input; you are not mutating the values after creation, after all.

like image 158
Martijn Pieters Avatar answered Dec 23 '25 22:12

Martijn Pieters