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


Groups > comp.lang.python > #101760

Re: Writing a stream of bytes

From Tim Chase <python.list@tim.thechases.com>
Newsgroups comp.lang.python
Subject Re: Writing a stream of bytes
Date 2016-01-15 10:05 -0600
Message-ID <mailman.17.1452874497.15297.python-list@python.org> (permalink)
References <n7b4os$9j2$1@ger.gmane.org>

Show all headers | View raw


On 2016-01-15 16:55, jmp wrote:
> 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

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


Thread

Re: Writing a stream of bytes Tim Chase <python.list@tim.thechases.com> - 2016-01-15 10:05 -0600

csiph-web