Next: A sampling of useful Up: numpy_arrays Previous: Vectors and Matrices

# Reading and writing vectors and matrices

The np.savetxt} and {\bf\verbnp.loadtxt| functions save and restore arrays:
  np.savetxt("M.txt", M) N = np.loadtxt("M.txt") 

Here we saved the numpy array M to a file called M.txt and then restored it to a numpy array called N. The default format here is to write the array one row per line with scientific notation and lots of digits:
  1.000000000000000000e+00 -2.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00 -4.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00 -6.000000000000000000e+00 3.000000000000000000e+00 4.000000000000000000e+00 -8.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00 -1.000000000000000000e+01 5.000000000000000000e+00 

With np.savetxt, you can control the format and add a "delimiter", i.e. something besides just a space to separate the numbers. Here is an example
  np.savetxt("M.txt", M, fmt="%5.2f", delimiter=",") N = np.loadtxt("M.txt", delimiter=",") 

In this case the file M.txt looks like this:
  1.00,-2.00, 1.00 2.00,-4.00, 2.00 3.00,-6.00, 3.00 4.00,-8.00, 4.00 5.00,-10.00, 5.00 

The format specifier %5.2f says to allow at least five spaces for the number and to show two digits past the decimal point without displaying a power of 10. The format specification is the one used by the ANSI C standard printf function. For a brief description of possible formats, see some C++ noteshttp://www.physics.utah.edu/ detar/lessons/c++/canned_classes/node7.html

Notice that if we use a non-blank delimiber, we must now specify the same delimiter with np.loadtxt.

Carleton DeTar 2018-02-12