Save a NumPy Array to a Text File in Python

You can save the NumPy array to a text file using the savetxt() function.

For example, imagine that we created an array called numpy_array, containing 8 values from -2 to 5. Next, we are going to use this command:

Open the text file to see how the array looks like.

You can also save individual items to an array, but you have to pass an individual element as a list.

If you pass an individual value without taking it into square brackets, it will result in an error.

ValueError: Expected 1D or 2D array, got 0D array instead

Formatting values with the fmt parameter

The savetxt() function can take multiple parameters. One of them is fmt. This parameter is responsible for formatting an array inside a text file.

Although I inserted integers, the values inside the text file are formatted as floating-point numbers with lots of zeros after the decimal point.

To change this, we can modify the function this way:

If we run the code and open the text file, it will show only integers.

Saving a 2D array to a file

We saved a 1D array to a file and it works fine, but the error message shows that we can also save a 2D array. There are at least two ways we can do it.

The first way is to use a 2D array as a parameter:

Another way to do it is to use the reshape() function. This function changes the shape of an array without changing its data.

Whichever method you choose, the data inside the file will be formatted the same way.

Load NumPy array from a file

After saving data into a text file we are going to load it into a NumPy array.

For this, we will use the np.loadtxt() function.

When you load data from a text file, you can also use the reshape() function to change the shape of the loaded data.

In this example, we inserted an array that looks like that:

[[-2, -1], [0, 1], [2, 3], [4, 5]]

After reshaping it, it takes a different form:

[[-2, -1, 0, 1], [2, 3, 4, 5]]

This is the whole code:

Run it to print the array.

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