Reading and Writing Arrays to/from Files in NumPy
NumPy provides functions for saving and loading arrays to and from files in various formats.
1. Importing NumPy
Before handling file operations, import NumPy.
import numpy as np
2. Saving and Loading Arrays in .npy Format
NumPy allows saving arrays in binary format using np.save()
and loading them using np.load()
.
Saving an Array
arr = np.array([10, 20, 30, 40, 50]) np.save("array.npy", arr)
Loading an Array
loaded_arr = np.load("array.npy") print(loaded_arr) # Output: [10 20 30 40 50]
3. Saving and Loading Arrays in Text Format
Use np.savetxt()
and np.loadtxt()
to save and read arrays in text format.
Saving an Array as a Text File
np.savetxt("array.txt", arr, delimiter=",")
Loading an Array from a Text File
loaded_txt_arr = np.loadtxt("array.txt", delimiter=",") print(loaded_txt_arr) # Output: [10. 20. 30. 40. 50.]
4. Conclusion
NumPy provides efficient methods to save and load arrays in both binary (.npy) and text formats for easy data storage and retrieval.