Hi pyple !

I'd like to write a stream of bytes into a file. I'd like to use the struct (instead of bytearray) module because I will have to write more than bytes.

let's say I want a file with 4 bytes in that order:

01 02 03 04

None of these work:

import struct

with open('toto', 'wb') as f: f.write(struct.pack('4B', *[1,2,3,4]))
with open('toto', 'wb') as f: f.write(struct.pack('<4B', *[1,2,3,4]))
with open('toto', 'wb') as f: f.write(struct.pack('>4B', *[1,2,3,4]))

I always end up with the following bytes on file:
!hexdump toto
0000000 0201 0403

Note: the '<' and '>' tells struct to pack for a litle/big endian architecture.

The only solution I came up with is

with open('toto', 'wb') as f: f.write(struct.pack('>4B', *[2,1,4,3]))

But I'd rather not manipulate the stream, as it seems to me that this would be the job of struct. Or maybe I completely overlooked the actual issue ?

Cheers,

jm

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

Reply via email to