Input/Output Operations in NumPy

Saving and loading NumPy arrays.

10 min read
Beginner

Input/Output Operations in NumPy

In this lesson, you will learn various ways of performing I/O (Input/Output) operations in NumPy.

NumPy provides built-in functions for efficiently saving NumPy arrays as external files in the disk and also for loading NumPy arrays from a saved file into your Python code.

Creating NPY and NPZ files in NumPy

Generally, NumPy arrays are saved in .npy or .npz file format.

The .npy file format is a simple format for saving NumPy arrays to disk with full information about them. It stores all information about a NumPy array including its dtype and shape so that the array can be reconstructed on any machine despite the machineโ€™s architecture. On the other hand, several arrays can be contained and saved into a single file in uncompressed .npz format.

The numpy.save() function is used to save an array in .npy format, whereas numpy.savez() is used to save an array in .npz format.

python
# Importing the NumPy library as np
import numpy as np

# Creating two 1-D numpy arrays
a = np.arange(start=1, stop=5, step=1)
b = np.arange(start=6, stop=10, step=1)

# Printing the arrays
print("a: ", a)
print("b: ", b)
a=[1234]\text{a} = \begin{bmatrix} 1 & 2 & 3 & 4 \end{bmatrix} b=[6789]\text{b} = \begin{bmatrix} 6 & 7 & 8 & 9 \end{bmatrix}

Saving the Numpy array a in .npy format,

python
# Saving the a to .npy format
np.save('a.npy', a)

Likewise, the numpy.load() function is used to load the array into the Python code.

python
# Loading saved array
a_loaded = np.load('a.npy')

# Printing the loaded data
print("a_loaded: ", a_loaded)

Saving the NumPy arrays a and b in .npz format,

python
# Saving the arrays a and b  to .npz format
np.savez('ab.npz', a, b)

While loading the .npz file, the individual array can be accessed by passing "arr_0, arr_1, โ€ฆ.. arr_n", as a key to the loaded object.

python
# Loading the saved arrays
ab_loaded = np.load('ab.npz')

print("First array in ab_loaded: ", ab_loaded['arr_0'])
print("Second array in ab_loaded: ", ab_loaded['arr_1'])

Saving and loading .txt files in NumPy

NumPy arrays can also be stored in plain .txt file formats. The numpy.savetxt() and numpy.loadtxt() methods are used to save and load arrays respectively.

python
# Creating a 1-D numpy arrays
a = np.arange(start=1, stop=5, step=1)

print("a: ", a)

# Saving array as a txt file
np.savetxt("a.txt", a)

# Loading array from txt file
loaded_arr = np.loadtxt("a.txt")

print("Loaded Array: ", loaded_arr)
a=[1234]\text{a} = \begin{bmatrix} 1 & 2 & 3 & 4 \end{bmatrix}

And, with that we've come to the end of this course!