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:
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.]]
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 in the same directory as the Python script.
Reading and writing files is a necessary skill for data analysis. We wrote to a file with savetxt()
. We made an identity matrix with the eye()
function.
Instead of a filename, we can also provide a file handle. A file handle is a term in many programming languages, which means a variable pointing to a file, like a postal address. For more information on how to get a file handle in Python, please refer to http://www.diveintopython3.net/files.html.
You can check for yourself whether the contents are as expected. The code for this example can be downloaded from the book support website: https://www.packtpub.com/books/content/support (see save.py
)
import numpy as np i2 = np.eye(2) print(i2) np.savetxt("eye.txt", i2))