numpy.savetxt() function in Python is used to save a NumPy array to a text file. It provides flexible options for formatting, delimiters, headers, footers and file encoding.
Syntax
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
Parameters
- fname: Name of the output file or file handle. If it ends with .gz, the file is saved in compressed gzip format. numpy.loadtxt() can read such files directly.
- X: Array data to be saved. Can be 1D or 2D.
- fmt: Format of the data values. Accepts a single format (e.g., '%10.5f') or multiple formats. Default is '%.18e' (exponential form).
- delimiter: String or character separating columns. Default is a single space ' '.
- newline: String separating lines. Default is '\n'.
- header: Text written at the beginning of the file.
- footer: Text written at the end of the file.
- comments: String prefixed to header and footer to mark them as comments. Default is '# '.
- encoding: Encoding for the output file. Default is 'latin1'. Older NumPy versions (<1.14) may not load files with other encodings.
Example 1: Saving a 1D NumPy Array
Outputx is:
[0 1 2 3 4 5 6 7 8 9]
The file contains:
0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
4.000000000000000000e+00
5.000000000000000000e+00
6....
Explanation:
- np.savetxt('geekfile.txt', x, delimiter=', '): Saves the array to a text file.
Each array element is written on a new line in the text file.
Default format: scientific notation with high precision. - f.read(): Displays file content showing stored array values.
Example 2: Saving Multiple Arrays
Outputx is: [0 1 2 3 4 5 6 7 8 9]
y is: [10 11 12 13 14 15 16 17 18 19]
z is: [20 21 22 23 24 25 26 27 28 29]
The file contains:
0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00 3...
Note: All arrays must have the same length (number of elements); otherwise, a TypeError will occur.
Explanation:
- np.arange(): Creates three arrays x, y, z with values 0–9, 10–19 and 20–29.
- np.savetxt('geekfile.txt', (x, y, z)): Saves all arrays as rows in a text file in scientific notation.
- open(..., 'r') + f.read(): Reads and displays the saved file content.
Example 3: Error When Arrays Have Unequal Dimensions