NumPy Tutorial NumPy Statistics NumPy References

NumPy - savetxt() function

The NumPy savetxt() function is used to save an array to a text file.

Note: To load arrays from text files, loadtxt() function is used.


numpy.savetxt(fname, X)


fname Required. Specify the filename to which the data is saved. If the filename ends in .gz, the file is automatically saved in compressed gzip format.
X Required. Specify data to be saved in the file (1D or 2D array_like).

Return Value



In the example below, array arr is saved into a text file called test.out. Further, the loadtxt() function is used to load the saved array from the file and print it.

import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])

#saving arr in text file - test.out
np.savetxt("test.out", arr)

#loading array from test.out
y = np.loadtxt("test.out")

#displaying the content of y

The output of the above code will be:

[10. 20. 30. 40. 50. 60.]


The example below describes how to save multiple numpy arrays in a file and load the saved arrays from it. Please note that, each array must have same number of elements.

import numpy as np

x = y = z = np.arange(0.0,5.0,1.0)
np.savetxt("demo.txt", (x, y, z))

#loading array from demo.txt
NewArr = np.loadtxt("demo.txt")

#displaying the result

The output of the above code will be:

[[0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]]

❮ NumPy - Functions