Labs ICT
Pro Login

Saving & Loading Data

Reading from and writing to files.

Saving & Loading Data

Data persistence is crucial. Think of it like saving your game progress - you don't want to start over every time. NumPy has efficient formats for this.

Binary Format (Fast)

np.save() and np.load() use NumPy's binary format.


import numpy as np

arr = np.array([1, 2, 3, 4, 5])
np.save('my_array.npy', arr)

loaded = np.load('my_array.npy')
print(f"Loaded: {loaded}")
    

Binary format is fast and preserves dtype perfectly. The file extension should be .npy.

Text Format (Human-readable)

np.savetxt() and np.genfromtxt() work with text files.


import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt('data.csv', arr, delimiter=',')

loaded = np.genfromtxt('data.csv', delimiter=',')
print(f"Loaded:\n{loaded}")
    

Here is the thing - text format is slower but you can open the file in Excel or any text editor.

Multiple Arrays

np.savez() saves multiple arrays in one file.


import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

np.savez('arrays.npz', array_a=a, array_b=b)

loaded = np.load('arrays.npz')
print(f"A: {loaded['array_a']}")
print(f"B: {loaded['array_b']}")
    

One thing that confused me at first was when to use which format. Use binary for speed, text for compatibility.

Try it Yourself →

Key Takeaways

  • np.save()/np.load() use fast binary format
  • np.savetxt()/np.genfromtxt() use human-readable text
  • np.savez() saves multiple arrays in one file
  • Binary is faster, text is more compatible