Saving data can be very beneficial when saving and restoring your work. It also serves as a backup where you do not have to recreate everything from scratch, in case of data loss.
NumPy savetxt Function
The NumPy savetxt() function allows you to store an array in a text file. The syntax is provided below:
Let us explain the function’s following parameters:
- fname – the filename under which to save the file into the array. You can also pass the filename as .gz, which saves the file into a compressed gzip
- x – refers to the array to be saved to the provided filename
- fmt – format option, such as %10.5f format
A single format, such as %10.5f, a sequence of formats, or a multi-format string. An example is “Iteration %d – %10.5f”, in which case the delimiter is ignored. For complex X, the legal options for fmt are:
- a single specifier, fmt= “%.4e”, resulting in numbers formatted like “(%s+%sj)” % (fmt, fmt)
- a full string specifying every real and imaginary part, such as “ %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej” for 3 columns
- a list of specifiers, one per column — in this case, the real and imaginary part must have separate specifiers, e.g. [‘%.3e + %.3ej’, ‘(%.15e%+.15ej)’] for 2 columns
This article discussed how to use the savetxt() function in NumPy to save an array into a text file. This function allows you to save and restore your files, when it serves as a backup. Check the other Linux Hint articles for more tips and tutorials.