Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #101758

Writing a stream of bytes

From jmp <jeanmichel@sequans.com>
Newsgroups comp.lang.python
Subject Writing a stream of bytes
Date 2016-01-15 16:55 +0100
Message-ID <mailman.16.1452873321.15297.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Writing a stream of bytes jmp <jeanmichel@sequans.com> - 2016-01-15 16:55 +0100
  Re: Writing a stream of bytes BartC <bc@freeuk.com> - 2016-01-15 16:04 +0000

csiph-web