Introduction
In this lab, you will learn how to use NumPy to read and write arrays to files. NumPy provides several functions for file input and output that make it easy to work with large datasets.
Achievements
- The
savetxt()function - The
save()function - The
loadtxt()function - The
genfromtxt()function - The
load()function
Writing Arrays to Files
NumPy provides several functions for writing arrays to files. The most common are savetxt and save.
Open the Python Shell
Open the Python shell by typing the following command in the terminal.
python3
Import NumPy
NumPy is already installed, you can import it in your Python code:
import numpy as np
Using Savetxt
The savetxt function is used to write arrays to text files. Here is an example:
data = np.random.rand(10, 5)
np.savetxt('data.txt', data, delimiter=',')
- This will write the contents of
datato a text file calleddata.txt, separating the values bycommas.
Using save
The save function is used to write arrays to binary files. Here is an example:
np.save('data.npy', data)
- This will write the contents of
datato a binary file calleddata.npy.
Reading Arrays from Files
NumPy provides several functions for reading arrays from files. The most common are loadtxt, genfromtxt and load.
Using loadtxt
The loadtxt function is used to read arrays from text files.Here is an example:
data = np.loadtxt('data.txt',delimiter=',')
print(data)
- This will read the contents of
data.txtinto a NumPy array, from step 1 we know that the values indata.txtare separated bycommas. - The code
print(data)will print the content read fromdata.txt.
Using Genfromtxt
The genfromtxt function is similar to loadtxt, but it can handle missing values and other special cases. Here is an example:
data = np.genfromtxt('data.txt', delimiter=',')
print(data)
- This will read the contents of
data.txtinto a NumPy array.
Using Load
The load function is used to read the arrays from binary files. Here is an example:
data = np.load('data.npy')
print(data)
- This will read the contents of
data.npyinto a NumPy array.
Summary
Congratulations! You have completed the NumPy File IO Lab.
In this lab, you learned how to:
- Use NumPy's
savetxt()andsave()functions to write arrays to files. - Use NumPy's
loadtxt(),genfromtxt()andload()functions to read arrays from files.



