Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #62180
| References | <3dcea919-82ad-4e0a-a00a-fa04ba39b1dd@googlegroups.com> |
|---|---|
| From | Oscar Benjamin <oscar.j.benjamin@gmail.com> |
| Date | 2013-12-17 11:21 +0000 |
| Subject | Re: [newbie] Saving binaries in a specific way |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.4277.1387279307.18130.python-list@python.org> (permalink) |
On 16 December 2013 22:19, Djoser <pedrovg000@gmail.com> wrote:
> Hi all,
Hi Djoser,
> I am new to this forum and also to Python, but I'm trying hard to understand it better.
> 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.
If you're coming from Matlab/Mathematica to Python you will likely
want to use the numpy library. This provides an array type that is
similar to Matlab arrays.
> I tried first to convert the number to binary using 'bin(number'), than I removed the '0b' and converted to 'Int16' or 'Int32', but with this approach I can't save a binary file using 'bytearray(').
Using numpy you can do this as follows:
import numpy as np
# Create arrays with the appropriate numeric types
first_numbers = np.array([12, -2, 10, -1], np.int16)
other_numbers = np.array([123, 123, 432, 543, 654, 654], np.int32)
# Output direct to binary file
with open('outputfile.bin', 'wb') as fout:
first_numbers.tofile(fout)
other_numbers.tofile(fout)
# Read back in from binary file
with open('outputfile.bin', 'rb') as fin:
first_numbers_read = np.fromfile(fin, np.int16, count=4)
other_numbers_read = np.fromfile(fin, np.int32)
# Print the data that we read back to check it's right.
print(first_numbers_read)
print(other_numbers_read)
Oscar
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