Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #101758 > unrolled thread
| Started by | jmp <jeanmichel@sequans.com> |
|---|---|
| First post | 2016-01-15 16:55 +0100 |
| Last post | 2016-01-15 16:04 +0000 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
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
| From | jmp <jeanmichel@sequans.com> |
|---|---|
| Date | 2016-01-15 16:55 +0100 |
| Subject | Writing a stream of bytes |
| Message-ID | <mailman.16.1452873321.15297.python-list@python.org> |
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
[toc] | [next] | [standalone]
| From | BartC <bc@freeuk.com> |
|---|---|
| Date | 2016-01-15 16:04 +0000 |
| Message-ID | <n7b54j$nn2$1@dont-email.me> |
| In reply to | #101758 |
On 15/01/2016 15: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
Why is the hex dump doing 16-bits at a time? Get a byte dump, then it
might actually be the right output.
Anyway, this seems to work:
data=bytearray([1,2,3,4])
f = open("output", "wb")
f.write(data)
f.close()
Doubtless there are plenty of other ways.
--
Bartc
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web