How to write list of integers to file with struct.pack_into?

Dieter Maurer dieter at handshake.de
Mon Oct 2 13:47:30 EDT 2023


Jen Kris wrote at 2023-10-2 00:04 +0200:
>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)
>
>for offset in range(len(qs_array)):
>  item_to_write= bytes(qs_array[offset])
>  struct.pack_into(buf,"<Q", offset, item_to_write)
>
>But I get the error "struct.error: embedded null character."

You made a lot of errors:

 * the signature of `struct.pack_into` is
   `(format, buffer, offset, v1, v2, ...)`.
   Especially: `format` is the first, `buffer` the second argument

 * In your code, `offset` is `0`, `1`, `2`, ...
   but it should be `0 *8`, `1 * 8`, `2 * 8`, ...

 * The `vi` should be something which fits with the format:
   integers in your case. But you pass bytes.

Try `struct.pack_into("<Q", buf, 0, *qs_array)`
instead of your loop.


Next time: carefully read the documentation and think carefully
about the types involved.



More information about the Python-list mailing list