Python ModulesNumpy TutorialNumpy File Operations

NumPy File Operations

Saving and loading data is an essential part of working with arrays in NumPy. NumPy provides several functions for efficiently handling file operations, such as reading and writing arrays to binary or text files.


Binary File Operations

Binary files save data in a compact format, making them faster and more efficient for storing large datasets.

Saving Arrays with save()

The save() function saves a NumPy array to a binary .npy file.

import numpy as np
 
# Create an array
array = np.array([1, 2, 3, 4, 5])
 
# Save the array
np.save('array.npy', array)

Loading Arrays with load()

The load() function loads a NumPy array from a .npy file.

# Load the array
loaded_array = np.load('array.npy')
print("Loaded Array:", loaded_array)

Output:

Loaded Array: [1 2 3 4 5]

Text File Operations

Text files store data in a human-readable format. NumPy provides functions like savetxt() and loadtxt() for working with text files.

Saving Arrays with savetxt()

The savetxt() function saves a NumPy array to a text file.

# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
 
# Save the array to a text file
np.savetxt('array.txt', array_2d, delimiter=',', fmt='%d')

Loading Arrays with loadtxt()

The loadtxt() function loads data from a text file into a NumPy array.

# Load the array from a text file
loaded_array_2d = np.loadtxt('array.txt', delimiter=',')
print("Loaded 2D Array:", loaded_array_2d)

Output:

Loaded 2D Array: [[1. 2. 3.]
                  [4. 5. 6.]]

Key Differences Between Binary and Text File Operations

AspectBinary FilesText Files
FormatCompact and efficientHuman-readable
Functionssave(), load()savetxt(), loadtxt()
Use CaseLarge datasets, fast I/OSmaller datasets, portability

Try It Yourself

Problem 1: Save and Load Binary File

Create a 1D array of integers from 1 to 10. Save it to a binary file and load it back.

Show Code
import numpy as np
 
# Create an array
array = np.arange(1, 11)
 
# Save to binary file
np.save('example.npy', array)
 
# Load from binary file
loaded_array = np.load('example.npy')
print("Loaded Array:", loaded_array)

Problem 2: Save and Load Text File

Create a 2D array of shape (3, 3). Save it to a text file using savetxt() and load it back using loadtxt().

Show Code
import numpy as np
 
# Create a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
 
# Save to text file
np.savetxt('example.txt', array_2d, delimiter=',', fmt='%d')
 
# Load from text file
loaded_array_2d = np.loadtxt('example.txt', delimiter=',')
print("Loaded 2D Array:", loaded_array_2d)

Pyground

Play with Python!

Output: