w3resource

How to save and load a NumPy array to and from a Binary file?

NumPy: I/O Operations Exercise-7 with Solution

Write a NumPy array to a binary file using np.save and then load it back using np.load.

Sample Solution:

Python Code:

import numpy as np

# Create a NumPy array
data_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Define the path to the binary file
binary_file_path = 'data.npy'

# Save the NumPy array to a binary file using np.save
np.save(binary_file_path, data_array)

# Load the NumPy array from the binary file using np.load
loaded_array = np.load(binary_file_path)

# Print the original and loaded NumPy arrays
print("Original NumPy Array:")
print(data_array)

print("\nLoaded NumPy Array from Binary File:")
print(loaded_array)

Output:

Original NumPy Array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Loaded NumPy Array from Binary File:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Explanation:

  • Import NumPy Library: Import the NumPy library to handle arrays.
  • Create NumPy Array: Define a NumPy array with some example data.
  • Define Binary File Path: Specify the path where the binary file will be saved.
  • Save Array to Binary File: Use np.save() to save the NumPy array to a binary file with the specified path.
  • Load Array from Binary File: Use np.load() to read the contents of the binary file back into a NumPy array.
  • Finally print the output of original NumPy array and the loaded array to verify that the data was saved and read correctly.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: How to save a NumPy array to a text file and read it back?
Next: How to save and load multiple NumPy arrays to and from a single binary file?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.