Using np.savetxt() in Python: Save NumPy Arrays to Text Files

Recently, I was working on a data analysis project where I needed to export NumPy arrays to text files that could be shared with team members who didn’t use Python. The solution? NumPy’s efficient np.savetxt() function.

In this article, I’ll show you everything you need to know about using np.savetxt() in Python to save your NumPy arrays to text files. I’ll cover the basic syntax, formatting options, and share some practical examples that you can use in your projects.

So let’s get in!

np.savetxt() Function in Python

The np.savetxt() function is a NumPy utility that allows you to save array data to a text file. It’s particularly useful when you need to:

  • Export data for use in other applications like Excel or MATLAB
  • Share results with colleagues who don’t use Python
  • Create CSV files from your NumPy arrays
  • Archive numerical data in a human-readable format

Read Python NumPy Matrix Operations

Basic Syntax and Parameters

Here’s the basic syntax of the np.savetxt() function:

np.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)

Let’s explore the key parameters:

  • fname: The filename or file handle where data will be saved
  • X: The array data to be saved
  • fmt: Format specifier for the data
  • delimiter: String that separates values in the output file
  • header: String to be written at the beginning of the file
  • footer: String to be written at the end of the file
  • comments: String that will be prepended to the header and footer

Check out 0-Dimensional Array NumPy in Python

Save NumPy Arrays to Text Files in Python

Now, I will explain how to save NumPy arrays to text files in Python.

Method 1 – Simple Array Export with Default Settings

The simplest way to use np.savetxt() is to provide just the filename and the Python array:

import numpy as np

# Create structured array
population_data = np.array([
    [39.5, "California"],
    [30.0, "Texas"],
    [21.8, "Florida"],
    [19.8, "New York"],
    [13.0, "Pennsylvania"]
], dtype=object)

# Print to console
print("Population (millions)\tState")
for row in population_data:
    print(f"{row[0]}\t{row[1]}")

# Save to text file
np.savetxt(
    'us_population.txt',
    population_data,
    fmt='%s\t%s',
    header='Population (millions)\tState',
    comments=''
)

Output:

Population (millions)   State
39.5    California
30.0    Texas
21.8    Florida
19.8    New York
13.0    Pennsylvania

You can refer to the screenshot below to see the output.

numpy savetxt append

However, this will attempt to convert all elements to float, which can cause issues with mixed data types. Let’s look at a better way to handle this.

Read NumPy Shape in Python

Method 2 – Format Output with the fmt Parameter

When working with specific data types or when you want to control how your data appears in the output file, the fmt parameter is your friend:

import numpy as np
import os

# Create numeric data - US GDP by quarter for 2022 (in trillion $)
gdp_data = np.array([
    [2022, 1, 24.386],
    [2022, 2, 24.978],
    [2022, 3, 25.723],
    [2022, 4, 26.138]
])

# Ensure the directory exists
directory = r'C:\Users\Public\code'
if not os.path.exists(directory):
    os.makedirs(directory)

# Define the file path
file_path = os.path.join(directory, 'us_gdp_2022.csv')

# Save with formatted output
np.savetxt(file_path, 
           gdp_data, 
           fmt='%d,%d,%.3f',  # Integer year, integer quarter, 3 decimal places for GDP
           header='Year,Quarter,GDP_Trillion',
           comments='')  # Empty comments to avoid # before header

print(f"File saved to {file_path}")

Output:

File saved to C:\Users\Public\code\us_gdp_2022.csv

You can refer to the screenshot below to see the output.

numpy savetxt

This creates a clean CSV file with properly formatted numbers and a header line.

Check out Create an Empty Array using NumPy in Python

Method 3 – Work with CSV Files using Delimiters

CSV files are one of the most common formats for data exchange. Here’s how to create them with np.savetxt():

import numpy as np

# US stock market data (date, open, high, low, close)
stock_data = np.array([
    ['2023-01-05', 3808.10, 3822.93, 3802.43, 3808.10],
    ['2023-01-06', 3807.40, 3906.19, 3807.40, 3895.08],
    ['2023-01-09', 3892.38, 3950.57, 3891.68, 3892.09],
    ['2023-01-10', 3888.57, 3919.83, 3877.29, 3919.25]
])

# Save as CSV with appropriate formatting
np.savetxt('sp500_data.csv', 
           stock_data, 
           fmt='%s,%.2f,%.2f,%.2f,%.2f',
           delimiter=',',  # Using comma as delimiter
           header='Date,Open,High,Low,Close',
           comments='')

The delimiter parameter ensures values are separated correctly, while the fmt parameter handles the mixed data types.

Read NumPy: Create a NaN Array in Python

Method 4 – Add Headers and Footers

For better documentation of your data, you can add headers and footers:

import numpy as np

# US temperature data for major cities (city, temp in F)
temp_data = np.array([
    [98.6, 102.3, 97.1, 99.5],
    [97.8, 101.2, 98.6, 100.1],
    [98.1, 103.4, 96.8, 98.7]
])

# Save with headers and footers
np.savetxt('patient_temperatures.csv', 
           temp_data, 
           fmt='%.1f', 
           delimiter=',',
           header='New York,Los Angeles,Chicago,Houston',
           footer='Data collected on 2023-01-15',
           comments='# ')

The comments parameter (#) adds a hash before the header and footer lines, marking them as comments in many data processing tools.

Check out NumPy Zeros in Python

Method 5 – Handle Complex Data Types

When working with complex data types, you might need to convert your data:

import numpy as np

# Complex data with mixed types
complex_data = np.array([
    (1, 'John', 'CEO', 250000),
    (2, 'Lisa', 'CTO', 225000),
    (3, 'Mike', 'CFO', 215000)
], dtype=[('id', 'i4'), ('name', 'U10'), ('position', 'U10'), ('salary', 'f8')])

# Convert structured array to a simpler format for savetxt
formatted_data = np.array([
    [row['id'], row['name'], row['position'], row['salary']] 
    for row in complex_data
])

# Save to file
np.savetxt('employee_data.csv', 
           formatted_data,
           fmt='%d,%s,%s,%.2f',
           delimiter=',',
           header='ID,Name,Position,Salary',
           comments='')

By converting the structured array to a simpler format first, we make it easier to save with np.savetxt().

Check out NumPy Read CSV with Header in Python

Method 6 – Load the Saved Data Back into Python

To complete the cycle, you can load the data back using np.loadtxt():

import numpy as np

# First, save some US sales data
sales_data = np.array([
    [1, 45000, 52000, 47000],
    [2, 42000, 49000, 44000],
    [3, 50000, 55000, 52000],
    [4, 47000, 51000, 49000]
])

np.savetxt('quarterly_sales.csv', 
           sales_data, 
           fmt='%d,%.2f,%.2f,%.2f',
           delimiter=',',
           header='Quarter,East,West,Central',
           comments='')

# Now load it back
loaded_data = np.loadtxt('quarterly_sales.csv', 
                         delimiter=',', 
                         skiprows=1)  # Skip the header row

print("Loaded data:", loaded_data)

The skiprows parameter in np.loadtxt() allows us to skip the header when loading the data back.

I explained six methods in this tutorial to save NumPy arrays to text files that are array exporting with default settings, formatting output with the fmt parameter, working with CSV files using a delimiter, handling complex data types, and loading the saved data back into Python.

Other Python articles 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.