May 11, 2024

Save NumPy Arrays (Matrices) to Files and Load Arrays (Matrices) from Files

In this Python and NumPy tutorial, we will learn how to

  1. Save NumPy arrays or matrices to files.
  2. Load NumPy arrays or matrices from files.

We will explain two approaches for saving/loading matrices and arrays. The first approach is based on saving the matrix values as txt files and the second approach is based on saving the matrix values as a binary file.

The YouTube tutorial accompanying this post is given below.

1. Save arrays (matrices) to text files and load arrays (matrices) from text files

In this approach, we save arrays to text files and we load arrays from text files. First, we define a random NumPy array (matrix)

# import NumPy
import numpy as np
# define a random matrix
randomMatrix= np.random.randn(2,3)

Then, we will save the matrix “randomMatrix” as a Comma Separated Value (“CSV”) file. To do that, we use the function “numpy.savetxt()”

# Approach 1: save matrix data to a text file
# save matrix data to a text file
np.savetxt('matrixFile.txt', randomMatrix , delimiter =',')

We specify the name of the file “matrixFile.txt”. Then, we specify the name of the source matrix, and finally, we specify the character used to separate the numbers. The text file “matrixFile.txt” is

-1.295845245434572579e+00,-8.581285371060370926e-02,2.071840529805057396e-01
-2.785221033481849462e-01,-3.807243169487183887e-01,-7.504849952279193381e-01

We can see that the entries are separated by commas, and new rows are started with new lines.

The load the matrix from the file, we use the function “numpy.loadtxt()”

# load data from the file
loadedMatrix1= np.loadtxt('matrixFile.txt', delimiter=',')
doubleCheck1=(randomMatrix==loadedMatrix1)

The matrix “doubleCheck1” is

array([[ True,  True,  True],
       [ True,  True,  True]])

2. Save arrays (matrices) to binary “npy” files and load arrays (matrices) from binary “npy” files

In this approach, we use binary “npy” files. The save a matrix or an array to a binary file, we use the following script

# Approach 2: save matrix data as a binary file
# save a matrix to a binary file in NumPy .npy format
# save the simulation data
np.save('matrixFileBinary.npy', randomMatrix)

To save the array/matrix to a file, we use the function “numpy.save()”. We specify the file name with the extension “npy”, and we specify the source matrix. The load the array/matrix from the file, we use the function “numpy.load()”:

# load the data from the matrix
loadedMatrix2 = np.load('matrixFileBinary.npy')
doubleCheck2=(randomMatrix==loadedMatrix2)

As a result, we obtain

array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]])