Time for action – reading and writing files

As an example of file I/O, we will create an identity matrix and store its contents in a file. Perform the following steps to do so:

  1. The identity matrix is a square matrix with ones on the main diagonal and zeroes for the rest. The identity matrix can be created with the eye function. The only argument we need to give the eye function is the number of ones. So, for instance, for a 2 x 2 matrix, write the following code:
    i2 = np.eye(2)
    print i2
    The output is:
    [[ 1.  0.]
    [ 0.  1.]]
  2. Save the data using the savetxt function. We obviously need to specify the name of the file that we want to save the data in and the array containing the data itself.
    np.savetxt("eye.txt", i2)

A file called eye.txt should have been created. You can check for yourself whether the contents are as expected. The code for this example can be downloaded from the book support website http://www.packtpub.com/support (see save.py).

import numpy as np

i2 = np.eye(2)
print i2
np.savetxt("eye.txt", i2)

What just happened?

Reading and writing files is a necessary skill for data analysis. We wrote to a file using savetxt. We made an identity matrix with the eye function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.151.141