How to Use np.savetxt and np.loadtxt in NumPy
Use
np.savetxt(filename, array) to save a NumPy array to a text file and np.loadtxt(filename) to load it back into an array. These functions handle plain text files and support options like delimiters and formatting for easy data exchange.Syntax
np.savetxt saves an array to a text file with options for delimiter and formatting. np.loadtxt reads a text file and returns a NumPy array.
- np.savetxt(filename, array, delimiter=' ', fmt='%.18e'):
filename - file path or object
array - data to save
delimiter - character separating values (default space)
fmt - format string for numbers (default scientific) - np.loadtxt(filename, delimiter=' ', dtype=float):
filename - file path or object
delimiter - character separating values
dtype - data type of loaded array
python
np.savetxt(fname, X, delimiter=' ', fmt='%.18e') np.loadtxt(fname, delimiter=' ', dtype=float)
Example
This example shows how to save a 2D array to a file and then load it back. It demonstrates using a comma as delimiter and formatting numbers with two decimals.
python
import numpy as np # Create a 2D array arr = np.array([[1.5, 2.3, 3.1], [4.7, 5.6, 6.2]]) # Save array to 'data.txt' with comma delimiter and 2 decimal places np.savetxt('data.txt', arr, delimiter=',', fmt='%.2f') # Load the array back from the file loaded_arr = np.loadtxt('data.txt', delimiter=',') print('Saved array:') print(arr) print('\nLoaded array:') print(loaded_arr)
Output
Saved array:
[[1.5 2.3 3.1]
[4.7 5.6 6.2]]
Loaded array:
[[1.5 2.3 3.1]
[4.7 5.6 6.2]]
Common Pitfalls
Common mistakes include:
- Not matching the delimiter in
np.loadtxtto the one used innp.savetxt, causing loading errors. - Saving non-numeric data without specifying
fmt, which can cause formatting issues. - Trying to save/load arrays with mixed data types, which
np.savetxtandnp.loadtxtdo not support well.
Example of a wrong and right way:
python
# Wrong: saving with comma delimiter but loading with default space delimiter import numpy as np arr = np.array([[1, 2], [3, 4]]) np.savetxt('wrong.txt', arr, delimiter=',') try: np.loadtxt('wrong.txt') # Will fail or load incorrectly except Exception as e: print('Error:', e) # Right: matching delimiter on load loaded = np.loadtxt('wrong.txt', delimiter=',') print('Loaded correctly:', loaded)
Output
Error: could not convert string to float: '1,2'
Loaded correctly: [[1. 2.]
[3. 4.]]
Quick Reference
| Function | Purpose | Key Parameters |
|---|---|---|
| np.savetxt | Save array to text file | filename, array, delimiter=' ', fmt='%.18e' |
| np.loadtxt | Load array from text file | filename, delimiter=' ', dtype=float |
Key Takeaways
Always match the delimiter in np.loadtxt to the one used in np.savetxt.
Use the fmt parameter in np.savetxt to control number formatting.
np.savetxt and np.loadtxt work best with numeric arrays, not mixed types.
These functions save and load data in plain text files for easy sharing.
Check file paths and permissions to avoid file read/write errors.