0
0
NumPydata~5 mins

np.savetxt() and np.loadtxt() for text in NumPy

Choose your learning style9 modes available
Introduction

We use np.savetxt() to save arrays as text files and np.loadtxt() to read them back. This helps keep data safe and shareable.

You want to save a small dataset from your analysis to share with a friend.
You need to store results from a calculation to use later without rerunning code.
You want to load data from a text file into your program for analysis.
You are working with simple numeric data and want a quick way to save and load it.
You want to save data in a readable format that can be opened in a text editor.
Syntax
NumPy
np.savetxt(filename, array, fmt='%.18e', delimiter=' ', header='', footer='', comments='# ')

np.loadtxt(filename, dtype=float, delimiter=' ', skiprows=0, usecols=None)

filename is the name of the file to save or load.

fmt controls how numbers are saved (like number of decimals).

Examples
Saves my_array to 'data.txt' with default format and space delimiter.
NumPy
np.savetxt('data.txt', my_array)
Loads data from 'data.txt' into a NumPy array.
NumPy
np.loadtxt('data.txt')
Saves array as CSV with two decimals per number.
NumPy
np.savetxt('data.csv', my_array, delimiter=',', fmt='%.2f')
Loads CSV data using comma as delimiter.
NumPy
np.loadtxt('data.csv', delimiter=',')
Sample Program

This program saves a 2x2 array to 'example.txt' with two decimals, then loads it back and prints both arrays to show they match.

NumPy
import numpy as np

# Create a simple 2D array
array = np.array([[1.2345, 2.3456], [3.4567, 4.5678]])

# Save the array to a text file with 2 decimal places
np.savetxt('example.txt', array, fmt='%.2f')

# Load the array back from the file
loaded_array = np.loadtxt('example.txt')

print('Saved array:')
print(array)
print('\nLoaded array:')
print(loaded_array)
OutputSuccess
Important Notes

When saving, the fmt controls how numbers appear. For example, '%.2f' means two decimals.

Loading assumes the file contains only numbers separated by the delimiter.

If your file has headers or comments, use skiprows to ignore them when loading.

Summary

np.savetxt() saves arrays to text files in a readable way.

np.loadtxt() reads numeric data from text files into arrays.

You can control formatting and delimiters to match your data needs.