How to write list of integers to file with struct.pack_into?
MRAB
python at mrabarnett.plus.com
Mon Oct 2 13:06:51 EDT 2023
On 2023-10-01 23:04, Jen Kris via Python-list wrote:
>
> Iwant to write a list of 64-bit integers to a binary file.
Everyexample I have seen in my research convertsit to .txt, but I want
it in binary. I wrote this code,based on some earlier work I have done:
>
> buf= bytes((len(qs_array)) * 8)
>
> foroffset in range(len(qs_array)):
>
> item_to_write= bytes(qs_array[offset])
>
> struct.pack_into(buf,"<Q", offset, item_to_write)
>
> ButI get the error "struct.error: embedded null character."
>
> Maybethere's a better way to do this?
>
You can't pack into a 'bytes' object because it's immutable.
The simplest solution I can think of is:
buf = struct.pack("<%sQ" % len(qs_array), *qs_array)
More information about the Python-list
mailing list