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

Learn, how to write a raw binary file with NumPy array data?
Submitted by Pranit Sharma, on March 05, 2023

Writing a raw binary file with NumPy array data

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.

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

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 code 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 »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.