[newbie] Saving binaries in a specific way
Tim Chase
python.list at tim.thechases.com
Mon Dec 16 17:48:56 EST 2013
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
.
More information about the Python-list
mailing list