NumPy np.savetxt()

This article will expand on using the savetxt() function in NumPy to save an array into a text file.

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:

numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None);

Let us explain the function’s following parameters:

  1. 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
  2. x – refers to the array to be saved to the provided filename
  3. 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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list