How to save a Python Numpy array to a text file?

Write a Numpy array to a text file with Python

In today’s tutorial we’ll show you two ways to export and save a Numpy array to a text or csv file which you can then further process. There are two different methods for accomplishing this task: use the Numpy function np.savetxt or save the array using the Pandas library

Step #1: Create Numpy array to export to file

We’ll start by defining a very simple array that you can use to follow along this example.


import numpy as np
import pandas as pd
my_array = np.arange(10,19).reshape(3,3)

Note: Numpy and Pandas are installed by default with Anaconda distributions. In case you are using a different distribution or a virtual environment you have manually built, you might need to import both libraries into your development environment namespace. Here’s how to troubleshoot Pandas or Numpy install issues.

Step #2: Save the array to a csv or txt file using Numpy.savetxt

We’ll first create a new file (could by csv, txt, json or others). Then we’ll loop through the array rows and write them into the file.

# open file with write access and write the array contents
with open('my_array.csv', 'w') as my_file:
        for i in my_array:
            np.savetxt(my_file,i)
print('Array exported to file')
Read the array from the file with Numpy

We can easily go the opposite way and import the file contents into a Numpy array with the loadtxt ndArray method.

my_array_2 = np.loadtxt('my_array.csv')
my_array_2.reshape(3,3)

Step #3: Write array contents to file with Pandas

We can use the very powerful Pandas Data Analysis library to export our array matrix to a file and read it back:

import pandas as pd
my_df = pd.DataFrame(my_array)
my_df.to_csv('my_array.csv',header = False, index= False)

Here are the contents of our comma separated value file:

We can obviously read the file back to Pandas by using:

my_df = pd.read_csv('my_array.csv',header = None)