[newbie] Saving binaries in a specific way

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Dec 17 06:21:18 EST 2013


On 16 December 2013 22:19, Djoser <pedrovg000 at 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



More information about the Python-list mailing list