How to Save an Array to a File in Python?

In this tutorial, I will explain how to save an array to a file in Python. As a Python developer working on a project for a US-based company, I recently encountered a situation where I needed to store a large NumPy array. We’ll explore different methods to save arrays to files using Python, along with practical examples.

Understanding Python NumPy Arrays

Before getting into saving arrays, let us recall what NumPy arrays are. NumPy in Python is very useful for working with arrays and performing many mathematical operations. It provides a more efficient array object. NumPy arrays are homogeneous, which means all elements must be of the same data type, and they can be multi-dimensional.

Consider the below example for creating a simple NumPy array in Python:

import numpy as np

customer_ages = np.array([25, 32, 47, 51, 29, 38])

In this example, we create a 1-dimensional array customer_ages containing the ages of customers.

Read NumPy array to a string in Python 

Save NumPy Arrays to Text Files in Python

One simple way to save a NumPy array is by storing it in a plain text file. This method will allow for easy sharing. We can use the numpy.savetxt() function to save an array to a text file. This function takes a filename and array as arguments and saves the array into a text file.

Here’s an example of saving the customer_ages array to a text file in Python:

import numpy as np

customer_ages = np.array([25, 32, 47, 51, 29, 38])
np.savetxt('customer_ages.txt', customer_ages)

You can see the screenshot below to understand how the file is created.

Save an Array to a File in Python

In the above example, we use np.savetxt() to save the customer_ages array to a file named customer_ages.txt. Array elements are separated by spaces in the text file by default.

You can also add another parameter to customize the output format. To save the array with comma-separated values (CSV), you can pass the delimiter argument:

np.savetxt('customer_ages.csv', customer_ages, delimiter=',')

You can see the screenshot below to understand how the file is created.

How to Save an Array to a File in Python

Check out NumPy Array to List in Python

Save Python NumPy Arrays to Binary Files

Saving arrays to text files is simple, but it is not an efficient method for saving large arrays. In those cases, we prefer saving arrays to binary files. Binary files offer faster read and write operations and take less disk space compared to text files.

To save a NumPy array to a binary file, we can use the numpy.save() function. This function allows you to save a single array to a binary file.

Consider an example of saving the customer_ages array to a binary file:

import numpy as np

customer_ages = np.array([25, 32, 47, 51, 29, 38])
np.save('customer_ages.npy', customer_ages)

You can see the screenshot below to understand how the file is created.

Save an Array to a File in Python to Binary Files

In the above example, we use np.save() to save the customer_ages array to a file named customer_ages.npy. The .npy extension is commonly used for NumPy binary files.

To load back the array from the binary file, you can use the numpy.load() function:

loaded_ages = np.load('customer_ages.npy')

Check out How to replace values in NumPy array by index in Python

Save Multiple NumPy Arrays to a File in Python

Sometimes, you may need to save multiple arrays to a single file. This can be useful when you have related data that you want to keep together. NumPy provides the numpy.savez() function to do this.

Here’s an example of saving multiple arrays to a file:

import numpy as np

customer_ages = np.array([25, 32, 47, 51, 29, 38])
customer_incomes = np.array([50000, 75000, 90000, 120000, 60000, 80000])

np.savez('customer_data.npz', ages=customer_ages, incomes=customer_incomes)

In the above example, we use np.savez() to save both the customer_ages and customer_incomes arrays to a file named customer_data.npz. We provide keyword arguments (ages and incomes) to assign names to the arrays in the file.

To load the arrays from the .npz file, you can use numpy.load() and access the arrays using their assigned names:

loaded_data = np.load('customer_data.npz')
loaded_ages = loaded_data['ages']
loaded_incomes = loaded_data['incomes']

Read Check if NumPy Array is Empty in Python

Handle Non-NumPy Arrays in Python

In some cases, you may have data stored in other formats, such as Python lists or dictionaries. To save these types of data to a file, you can first convert them to NumPy arrays using numpy.array() and then use the appropriate saving method.

For example, let’s say we have customer names stored in a Python list:

customer_names = ['John Doe', 'Jane Smith', 'Michael Johnson', 'Emily Davis', 'David Wilson', 'Sarah Anderson']

To save this list to a file, we can convert it to a NumPy array first:

names_array = np.array(customer_names)
np.savetxt('customer_names.txt', names_array, fmt='%s')

In the above code, we convert the customer_names list to a NumPy array using np.array(). Then we use np.savetxt() it to save the array to a text file named customer_names.txt. The fmt argument is set to '%s' specify that the array elements are strings.

Check out Find the Number of Elements in a Python Array

Conclusion

In this article, I explained what are NumPy arrays, and we discussed various ways to save arrays to a file in Python, that is saving NumPy arrays to text files, saving NumPy arrays to binary files, and saving multiple NumPy arrays to a file. I also showed how to handle non-NumPy arrays in Python.

I hope this tutorial helped you better understand how to save an array to a file in Python.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.