np.savetxt() function in Python [5 Examples]

In this NumPy article, I will explain what the np.savetxt() function in Python is, its syntax, the parameters required, and the return values. We will also see some of the use cases of the np.savetxt in Python.

The np.savetxt() is designed to save two-dimensional arrays to a text file, allowing for efficient storage and sharing of data. It provides a range of parameters to control the format, delimiter, header, and other aspects of the output file.

np.savetxt() Function in Python Syntax

The basic syntax of np.savetxt() function in Python is as follows:

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

NumPy savetxt Function in Python Parameters

Here,

  1. fname: File name or a file handle. If the filename ends in .gz, the file is automatically saved in compressed gzip format.
  2. X: The array to be saved. It should be a 2D array in Python.
  3. fmt: A format string or sequence of format strings, controlling the format of individual columns.
  4. delimiter: String or character separating columns.
  5. newline: String or character separating lines.
  6. header: String that will be written at the beginning of the file.
  7. footer: String that will be written at the end of the file.
  8. comments: String that will be prepended to the header and footer strings, to mark them as comments.

savetxt Python Function Return Values

The np.savetxt() function in Python, does not return a value but writes the array to a file in the specified format.

numpy.savetxt function in Python use cases

Let’s see some of the use cases of the np.savetxt() function in Python:

1. np savetxt function in Python

The np.savetxt() function in Python is used to save the 2D NumPy array data into a text file. The default settings are used, which means data is formatted as floating-point numbers and separated by spaces.

import numpy as np

temperature_data = np.array([[58, 62], [60, 64], [59, 65], [61, 66], [63, 68], [65, 70], [66, 71]])
np.savetxt('nyc_temperature_data.txt', temperature_data)

with open('nyc_temperature_data.txt', 'r') as file:
    nyc_temp_data = file.read()
    print("New York City Temperature Data:\n", nyc_temp_data)

Output:

New York City Temperature Data:
 5.800000000000000000e+01 6.200000000000000000e+01
6.000000000000000000e+01 6.400000000000000000e+01
5.900000000000000000e+01 6.500000000000000000e+01
6.100000000000000000e+01 6.600000000000000000e+01
6.300000000000000000e+01 6.800000000000000000e+01
6.500000000000000000e+01 7.000000000000000000e+01
6.600000000000000000e+01 7.100000000000000000e+01

Displayed below is a screenshot capturing the outcome of the code execution in the PyCharm editor.

np.savetxt() function in Python

2. Python savetxt function in NumPy with specifying a format

The array data is saved into the txt file, but with a format specifier %d, which means each number is saved as an integer. This changes the default floating-point representation to integer format.

import numpy as np

stock_prices = np.array([[152.35], [153.40], [154.55], [152.75], [153.80]])
np.savetxt('stock_prices.txt', stock_prices, fmt='%.2f')

with open('stock_prices.txt', 'r') as file:
    stock_prices_data = file.read()
    print("Stock Prices Data:\n", stock_prices_data)

Output:

Stock Prices Data:
 152.35
153.40
154.55
152.75
153.80

The following screenshot illustrates the results obtained from executing the code in the PyCharm editor.

np.savetxt() in Python

3. savetxt NumPy function in Python using delimiters

The array is saved to a txt file in Python, using a comma, as the delimiter between values in each row. This is useful for creating CSV (comma-separated values) files.

import numpy as np

baseball_stats = np.array([[5, 8, 0], [3, 7, 1], [6, 9, 0], [4, 6, 2]])
np.savetxt('baseball_stats.csv', baseball_stats, delimiter=',')

with open('baseball_stats.csv', 'r') as file:
    baseball_stats_data = file.read()
    print("Baseball Statistics Data:\n", baseball_stats_data)

Output:

Baseball Statistics Data:
 5.000000000000000000e+00,8.000000000000000000e+00,0.000000000000000000e+00
3.000000000000000000e+00,7.000000000000000000e+00,1.000000000000000000e+00
6.000000000000000000e+00,9.000000000000000000e+00,0.000000000000000000e+00
4.000000000000000000e+00,6.000000000000000000e+00,2.000000000000000000e+00

After executing the code in Pycharm, one can see the output in the below screenshot.

np.savetxt python

4. NumPy savetxt header in Python

To add a header to the text file we can use the np.savetxt() function in Python. They are useful for providing additional information or context about the data.

import numpy as np

demographic_data = np.array([[25, 45000], [32, 55000], [45, 62000], [29, 48000]])
np.savetxt('la_demographics.txt', demographic_data, header='Age, Income Bracket', comments='# ')

with open('la_demographics.txt', 'r') as file:
    la_demo_data = file.read()
    print("Los Angeles Demographic Data:\n", la_demo_data)

Output:

Los Angeles Demographic Data:
 # Age, Income Bracket
2.500000000000000000e+01 4.500000000000000000e+04
3.200000000000000000e+01 5.500000000000000000e+04
4.500000000000000000e+01 6.200000000000000000e+04
2.900000000000000000e+01 4.800000000000000000e+04

A screenshot is mentioned below, after implementing the code in the Pycharm editor.

np.savetxt header in Python

5. NumPy savetxt append in Python

Normally, numpy.savetxt() overwrites the existing file. To append data instead, you need to open the file in append mode and pass the file handle to numpy.savetxt().

import numpy as np

temperature_data = np.array([[58, 62], [60, 64], [59, 65], [61, 66]])
np.savetxt('nyc_temperature_data.txt', temperature_data)

additional_data = np.array([[67, 72], [68, 73]])
with open('nyc_temperature_data.txt', 'ab') as f:
    np.savetxt(f, additional_data)

with open('nyc_temperature_data.txt', 'r') as file:
    updated_nyc_temp_data = file.read()
    print("Updated New York City Temperature Data:\n", updated_nyc_temp_data)

Output:

Updated New York City Temperature Data:
 5.800000000000000000e+01 6.200000000000000000e+01
6.000000000000000000e+01 6.400000000000000000e+01
5.900000000000000000e+01 6.500000000000000000e+01
6.100000000000000000e+01 6.600000000000000000e+01
6.700000000000000000e+01 7.200000000000000000e+01
6.800000000000000000e+01 7.300000000000000000e+01

After implementing the code in the Pycharm editor, the screenshot is mentioned below.

np.savetxt append in Python

Conclusion

This article, provides a detailed explanation of the np.savetxt() function in Python, including its syntax, necessary parameters, and return values. Additionally, I’ve illustrated various practical applications of the np.savetxt() function in Python through several examples.

You may also like to read: