How to write a raw binary file with NumPy array data?

Learn, how to write a raw binary file with NumPy array data?
By Pranit Sharma Last updated : December 25, 2023

A binary file is just like any other content file which contains binary format content (a series of sequential bytes).

Problem statement

Suppose that we are given a numpy array of float values and we need to save the content of this array into a raw binary file as signed integers.

Write a raw binary file with NumPy array data

To write a raw binary file with NumPy array data, we can simply change the data type of the array to int16 using the astype() method and then we can use the tofile() method to save the content into a binary file. The tofile() method writes an array to a file as text or binary (default). The Data is always written in 'C' order, independent of the order of a.

Let us understand with the help of an example,

Python program to write a raw binary file with NumPy array data

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.random.random(10)

# Display Original array
print("Original array:\n",arr,"\n")

# Saving array as a file
arr.astype('int16').tofile('arr')

# Display result
print("File saved:\n\n")

Output

Example: How to write a raw binary file with NumPy array data?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.