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).
解决方案
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.