w3resource
NumPy Exercises

NumPy: Save a given array to a binary file

NumPy: Basic Exercise-35 with Solution

Write a NumPy program to save a given array to a binary file.

Sample Solution :

Python Code :

import numpy as np
import os
a = np.arange(20)
np.save('temp_arra.npy', a)
print("Check if 'temp_arra.npy' exists or not?")
if os.path.exists('temp_arra.npy'):
    x2 = np.load('temp_arra.npy')
    print(np.array_equal(a, x2))

Sample Output:

Check if 'temp_arra.npy' exists or not?
True                         

Python Code Editor:


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

Previous: Write a NumPy program to add a vector to each row of a given matrix.
Next: Write a NumPy program to save two given arrays into a single file in compressed format (.npz format) and load it.

What is the difficulty level of this exercise?