File Handling Using NumPy
NumPy provides built-in functions to save arrays to disk and load them back later, letting you persist data between sessions without needing to regenerate or recalculate it every time.
Saving and Loading Binary .npy Files
NumPy's native binary format (.npy) is the fastest and most space-efficient way to store an array, preserving its exact shape and data type.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
np.save("my_array.npy", arr) # save to disk
loaded = np.load("my_array.npy") # load back from disk
print(loaded) # [1 2 3 4 5]
Saving Multiple Arrays Together
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.savez("arrays.npz", first=a, second=b)
data = np.load("arrays.npz")
print(data["first"]) # [1 2 3]
print(data["second"]) # [4 5 6]
Working with Text and CSV Files
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt("data.csv", arr, delimiter=",")
loaded = np.loadtxt("data.csv", delimiter=",")
print(loaded)
Use .npy/.npz files when working purely within Python and NumPy for speed and efficiency, but use .csv or .txt formats when the data needs to be readable by other tools, like Excel, or shared with non-Python systems.
Coming Up Next
To close out this module, the final topic covers array creation shortcuts and logic functions for comparing and filtering array data.