Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #62114
| Date | 2013-12-16 16:48 -0600 |
|---|---|
| From | Tim Chase <python.list@tim.thechases.com> |
| Subject | Re: [newbie] Saving binaries in a specific way |
| References | <3dcea919-82ad-4e0a-a00a-fa04ba39b1dd@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.4241.1387234067.18130.python-list@python.org> (permalink) |
On 2013-12-16 14:19, Djoser wrote:
> I am new to this forum and also to Python, but I'm trying hard to
> understand it better.
Welcome aboard!
> I need to create a binary file, but the first 4 lines must be in
> signed-Integer16 and all the others in signed-Integer32. I have a
> program that does that with Matlab and other with Mathematica, but
> I'm converting all for Python.
You seem to be conflating ideas here: a binary file doesn't really
have "lines". Do you mean "first 4 bytes"? If so, then a
signed-Integer16 really only occupies 2 bytes, so you'd have to pad
it somehow. That said, I suspect that the "struct" module will get
you what you want:
from struct import pack
header16bit = 31415
data = list(range(10))
with open('output.bin', 'wb') as f:
f.write(pack('h', header16bit))
for signed_32bit_number in data:
f.write(pack('i', signed_32bit_number))
f.write(other_stuff)
You might need to specify the byte-ordering, which you can do by
prefixing the "h" or "i" with ">", "<" or "=" s documented at [1]
-tkc
[1]
http://www.python.org/doc//current/library/struct.html
.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
[newbie] Saving binaries in a specific way Djoser <pedrovg000@gmail.com> - 2013-12-16 14:19 -0800
Re: [newbie] Saving binaries in a specific way Chris Kaynor <ckaynor@zindagigames.com> - 2013-12-16 14:28 -0800
Re: [newbie] Saving binaries in a specific way Djoser <pedrovg000@gmail.com> - 2013-12-16 14:35 -0800
Re: [newbie] Saving binaries in a specific way Tim Chase <python.list@tim.thechases.com> - 2013-12-16 16:48 -0600
Re: [newbie] Saving binaries in a specific way Djoser <pedrovg000@gmail.com> - 2013-12-16 15:30 -0800
Re: [newbie] Saving binaries in a specific way rusi <rustompmody@gmail.com> - 2013-12-16 17:01 -0800
Re: [newbie] Saving binaries in a specific way Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2013-12-17 11:21 +0000
Re: [newbie] Saving binaries in a specific way Djoser <pedrovg000@gmail.com> - 2013-12-17 10:54 -0800
csiph-web