Reputation: 8273
I have a large list of values, which I want written to a file, as short integers.
I want to do this efficiently, and in Python3.
One value at a time, is possible using the struct module:
struct.pack( "h", val )
It is possible to prefix the format entry with a count, like so:
struct.pack( "4h", val0,val1,val2,val3 )
But when I try to construct the format dynamically, and write it in one go, I can't feed in a list.
For example:
values = [ x for x in range(100) ]
fmt = "%dh" % ( len(values), )
p = struct.pack( fmt, values )
Will give the error: struct.error: pack expected 100 items for packing (got 1)
How can I efficiently dump a large number of short integers into a file?
Basically, the Python equivalent of the C code:
short values[100];
fwrite( values, sizeof(values), 1, f);
Or am I forced to write these values one at a time if I use Python?
Upvotes: 1
Views: 246