NumPy offers input/output (I/O) functions for loading and saving data to and from files.
Input/output functions support a variety of file formats, including binary and text formats.
- The binary format is designed for efficient storage and retrieval of large arrays.
- The text format is more human-readable and can be easily edited in a text editor.
Most Commonly Used I/O Functions
Here are some of the commonly used NumPy Input/Output functions:
Function | Description |
---|---|
save() |
saves an array to a binary file in the NumPy .npy format. |
load() |
loads data from a binary file in the NumPy .npy format |
savetxt() |
saves an array to a text file in a specific format |
loadtxt() |
loads data from a text file. |
NumPy save() Function
In NumPy, the save()
function is used to save an array to a binary file in the NumPy .npy
format.
Here's the syntax of the save()
function,
np.save(file, array)
file
- specifies the file name (along with path if required)array
- specifies the NumPy array to be saved
Now, let's see an example.
import numpy as np
# create a NumPy array
array1 = np.array([[1, 3, 5],
[7, 9, 11]])
# save the array to a file
np.save('file1.npy', array1)
Here, we saved the NumPy array named array1 to the binary file named file1.npy
in our current directory.
NumPy load() Function
In the previous example, we saved an array to a binary file. Now we'll load that saved file using the load()
function.
Let's see an example.
import numpy as np
# load the saved NumPy array
loaded_array = np.load('file1.npy')
# display the loaded array
print(loaded_array)
Output
[[ 1 3 5] [ 7 9 11]]
Here, we have used the load()
function to read a binary file named file1.npy
. This is the same file we created and saved using save()
function in the last example.
NumPy savetxt() Function
In NumPy, we use the savetxt()
function to save an array to a text file.
Here's the syntax of the savetxt()
function:
np.save(file, array)
file
- specifies the file namearray
- specifies the NumPy array to be saved
Now, let's see an example,
import numpy as np
# create a NumPy array
array2 = np.array([[1, 3, 5],
[7, 9, 11]])
# save the array to a file
np.savetxt('file2.txt', array2)
The code above will save the NumPy array array2 to the text file named file2.txt
in our current directory.
NumPy loadtxt() Function
We use the loadtxt()
function to load the saved txt
file.
Let's see an example to load the file2.txt
file that we saved earlier.
import numpy as np
# load the saved NumPy array
loaded_array = np.loadtxt('file2.txt')
# display the loaded array
print(loaded_array)
Output
[[1. 3. 5.] [7. 9. 11.]]
Here, we have used the loadtxt()
function to load the text file named file2.txt
that was previously created and saved using the savetxt()
function.
Note: The values in the loaded array have dots .
because loadtxt()
reads the values as floating point numbers by default.