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

Barry barry at barrys-emacs.org
Mon Oct 2 12:08:35 EDT 2023


     On 2 Oct 2023, at 16:02, Jen Kris via Python-list
     <python-list at python.org> 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)

   buf is not writable so cannot be used by pack_into. I think you need to
   use bytesarray not bytes.

     foroffset in range(len(qs_array)):
     item_to_write= bytes(qs_array[offset])
     struct.pack_into(buf,"<Q", offset, item_to_write)

   You have the parameters in the wrong order.

struct.pack_into(format, buffer, offset, v1, v2, ...)[1]¶

        Pack the values v1, v2, … according to the format string format and
        write the packed bytes into the writable buffer buffer starting at
        position offset. Note that offset is a required argument.

          ButI get the error "struct.error: embedded null character."

        The nul is because you past buf of 0’s as the format.

     Maybethere's a better way to do this?

     Anyhelp will be very appreciated.
     Thanks. 

   Barry

     --
     https://mail.python.org/mailman/listinfo/python-list

References

   Visible links
   1. Permalink to this definition
	https://docs.python.org/3/library/struct.html#struct.pack_into


More information about the Python-list mailing list