Unlike np.save()'s binary .npy format, savetxt() produces a human-readable text file, making it suitable for exporting data to be inspected manually, opened as a CSV in a spreadsheet, or read by tools outside the NumPy/Python ecosystem — but at the cost of larger file sizes and potential precision loss, since every number gets converted to a fixed-precision text representation via the fmt parameter, and rereading that text can't always recover the exact original binary floating-point value. savetxt() only supports 1D and 2D arrays; higher-dimensional arrays need to be reshaped or saved a different way.
1Understanding np.savetxt()
Unlike np.save()'s binary .npy format, savetxt() produces a human-readable text file, making it suitable for exporting data to be inspected manually, opened as a CSV in a spreadsheet, or read by tools outside the NumPy/Python ecosystem — but at the cost of larger file sizes and potential precision loss, since every number gets converted to a fixed-precision text representation via the fmt parameter, and rereading that text can't always recover the exact original binary floating-point value. savetxt() only supports 1D and 2D arrays; higher-dimensional arrays need to be reshaped or saved a different way.
savetxt() converts numbers to text using a fixed format string, which can silently lose some floating-point precision — use np.save() instead of savetxt() whenever exact, lossless round-tripping of the data matters more than human readability or interoperability.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt("data.csv", arr, delimiter=",", fmt="%d")
with open("data.csv") as f:
print(f.read())2Practical Example
Here is a real-world application of np.savetxt() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([3.14159265358979, 2.71828182845905])
np.savetxt("precise.txt", arr, fmt="%.4f")
with open("precise.txt") as f:
print(f.read())3Best Practices
Follow these guidelines when working with np.savetxt():
1. Use savetxt() specifically when the output needs to be human-readable, opened in a spreadsheet, or read by a non-NumPy tool
2. Set an appropriate fmt string explicitly when the default scientific-notation formatting isn't what you want for the output file
3. Use np.save() instead of savetxt() when exact precision and fast round-tripping matter more than readability or external tool compatibility
Tip: savetxt() converts numbers to text using a fixed format string, which can silently lose some floating-point precision — use np.save() instead of savetxt() whenever exact, lossless round-tripping of the data matters more than human readability or interoperability.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt("data.csv", arr, delimiter=",", fmt="%d")
with open("data.csv") as f:
print(f.read())