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

Jen Kris jenkris at tutanota.com
Mon Oct 2 14:15:03 EDT 2023


Dieter, thanks for your comment that:

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

But you concluded with essentially the same solution proposed by MRAB, so that would obviate the need to write item by item because it writes the whole buffer at once.  

Thanks for your help.  


Oct 2, 2023, 17:47 by dieter at handshake.de:

> 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