NumPy provides several functions to save and load arrays. The most commonly used file formats for saving NumPy arrays are
.npy (NumPy binary format):
- This format is efficient for saving and loading single NumPy arrays.
- Use np.save() and np.load() functions.
import numpy as np
# Save a NumPy array
array_to_save = np.array([1, 2, 3])
np.save('saved_array.npy', array_to_save)
# Load a saved NumPy array
loaded_array = np.load('saved_array.npy')
print(loaded_array)
.npz (NumPy compressed archive):
- This format is suitable for saving multiple NumPy arrays in a single file.
- Use np.savez() or np.savez_compressed() to save, and np.load() to load.
import numpy as np
# Save multiple NumPy arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
np.savez('saved_arrays.npz', arr1=array1, arr2=array2)
# Load the saved NumPy arrays
loaded_data = np.load('saved_arrays.npz')
loaded_array1 = loaded_data['arr1']
loaded_array2 = loaded_data['arr2']
print(loaded_array1, loaded_array2)
.txt or .csv (Text or CSV format):
- If you want human-readable files, you can save NumPy arrays as text or CSV files.
- Use np.savetxt() and np.loadtxt() functions for plain text, or np.savetxt() with a delimiter for CSV.
import numpy as np
# Save a NumPy array as text
array_to_save = np.array([1, 2, 3])
np.savetxt('saved_array.txt', array_to_save)
# Load a saved NumPy array from text
loaded_array = np.loadtxt('saved_array.txt')
print(loaded_array)
Choose the file format based on your needs, and note that binary formats like .npy are more efficient for large arrays, while text formats are more human-readable.