DEV Community

Punitha
Punitha

Posted on

NumPy File I/O

What is File I/O?

  • I/O means Input and Output.
  • Save arrays to files.
  • Load arrays from files.

Save Array as .npy

  • NumPy provides np.save() to save an array in NumPy's .npy format.

Step 1:

np.save("numpy.npy", a)
Enter fullscreen mode Exit fullscreen mode

This saves the array as:

numpy.npy
Enter fullscreen mode Exit fullscreen mode

Save Array as CSV

  • You can also save an array as a CSV file using np.savetxt().

Step 1:

np.savetxt("numpy.csv", a, delimiter=",")
Enter fullscreen mode Exit fullscreen mode
  • "numpy.csv" → output file name
  • a → array to save
  • delimiter="," → values are separated by commas

Your file uses np.savetxt() with a comma delimiter.

Load Data from CSV

  • Use np.loadtxt() to read numerical data from a text/CSV file.

Step 1:

b = np.loadtxt("numpy.csv", delimiter=",")
Enter fullscreen mode Exit fullscreen mode

Step 2:

Print the loaded data:

print(b)
Enter fullscreen mode Exit fullscreen mode

Quick Reference

Function             Purpose

np.array()     -  Create an array
np.arange()    -  Create a sequence of numbers
reshape()      -  Change array shape
np.zeros()     -  Create an array filled with 0
np.ones()      -  Create an array filled with 1
np.empty()     -  Create an uninitialized array
np.full()      -  Create an array filled with a specified value
np.save()      -  Save an array as .npy
np.savetxt()       -  Save an array as text/CSV
np.loadtxt()       -  Load numerical data from text/CSV
Enter fullscreen mode Exit fullscreen mode

Top comments (0)