Save & Load NumPy Array to File | Python

NumPy Array to CSV File (ASCII)

The NumPy arrays can be saved to CSV files using the savetxt() function. File name & arrays(1D, 2D etc.) arguments used toe saves the array into CSV format. Delimiter is the character used to separate each variable in the file which must be set.

## save numpy array as csv file
from numpy import asarray
from numpy import savetxt
# define data
data = asarray([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
# save to csv file
savetxt('data.csv', data, delimiter=',')

Data from file can be loaded using loadtext() function by specifying the filename and the same comma delimiter.

## load numpy array from csv file
from numpy import loadtxt
# load array
data = loadtxt('data.csv', delimiter=',')
# print the array
print(data)

NumPy Array .NPY File (Binary)

The NumPy arrays can be saved to files in binary format using the save() NumPy function by specifying filename and the array to be saved. This format is efficient for saving & loading large amount of data.

## save numpy array as npy file
from numpy import asarray
from numpy import save
# define data
data = asarray([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
# save to npy file
save('data.npy', data)

Binary data from file can be loaded as NumPy array using load() function by specifying the filename.

## load numpy array from npy file
from numpy import load
# load array
data = load('data.npy')
# print the array
print(data)

NumPy Array to .NPZ File (compressed)

The NumPy arrays can be saved to compressed NPZ files using the savez_compressed() NumPy function. File name & arrays(1D, 2D etc.) arguments used to save large amount of data in gigabytes in compressed format. Multiple NumPy arrays can be saved to single compressed .npz file.

## save numpy array as npz file
from numpy import asarray
from numpy import savez_compressed
# define data
data = asarray([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
# save to npy file
savez_compressed('data.npz', data)

Data from file can be loaded using load() function. As savez_compressed() function supports saving multiple arrays to a single file, hence, the load() function may load multiple arrays.

The loaded arrays are returned from the load() function in a dict with the names ‘arr_0’ for the first array, ‘arr_1’ for the second, and so on.

## load numpy array from npz file
from numpy import load
# load dict of arrays
dict_data = load('data.npz')
# extract the first array
data = dict_data['arr_0']
# print the array
print(data)