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

Jen Kris jenkris at tutanota.com
Mon Oct 2 13:33:58 EDT 2023


Thanks very much, MRAB.  I just tried that and it works.  What frustrated me is that every research example I found writes integers as strings.  That works -- sort of -- but it requires re-casting each string to integer when reading the file.  If I'm doing binary work I don't want the extra overhead, and it's more difficult yet if I'm using the Python integer output in a C program.  Your solution solves those problems.  



Oct 2, 2023, 17:11 by python-list at python.org:

> 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)
> -- 
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list