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

Roel Schroeven roel at roelschroeven.net
Tue Oct 3 16:06:11 EDT 2023



Jen Kris via Python-list schreef op 2/10/2023 om 17:06:
> My previous message just went up -- sorry for the mangled formatting.  Here it is properly formatted:
>
> I want to write a list of 64-bit integers to a binary file.  Every example I have seen in my research converts it 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)

Shouldn't the two first parameters be swapped, like this?

         struct.pack_into("<Q", buf, offset, item_to_write)


Also it wouldn't surprise me if you had to use offset*8 instead of just 
offset in that pack_into() call -- I would think the offset is specified 
in bytes.

-- 
"In the old days, writers used to sit in front of a typewriter and stare out of
the window. Nowadays, because of the marvels of convergent technology, the thing
you type on and the window you stare out of are now the same thing.”
         -- Douglas Adams


More information about the Python-list mailing list