Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

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.

Note

In this and other chapters, we will use the following line by convention to import NumPy:

import numpy as np

Perform the following steps to do so:

  1. The identity matrix is a square matrix with ones on the main diagonal and zeros for the rest (see https://www.khanacademy.org/math/precalculus/precalc-matrices/zero-identity-matrix-tutorial/v/identity-matrix).

    The identity matrix can be created with the eye() function. The only argument that we need to give the eye() function is the number of ones. So, for instance, for a two-by-two matrix, write the following code:

    i2 = np.eye(2)
    print(i2)

    The output is:

    [[ 1.  0.]
    [ 0.  1.]]
  2. Save the data in a plain text file with the savetxt() function. 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...