English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NumPy IO

NumPy introduces a simple file format for ndarray objects: npy.

npy files are used to store data, graphics, dtype, and other information required to reconstruct ndarray.

Common IO functions include:

The load() and save() functions are the two main functions for reading and writing file array data. By default, arrays are saved in the uncompressed raw binary format in files with the .npy extension. The savetxt() function is used to write multiple arrays to a file. By default, arrays are saved in the uncompressed raw binary format in files with the .npz extension. The loadtxt() and savetxt() functions handle normal text files (.txt, etc.)

numpy.save()

The numpy.save() function saves the array to a file with the .npy extension.
numpy.save(file, arr, allow_pickle=True, fix_imports=True)

Parameter description:

file: The file to be saved, with an extension of .npy. If the file path does not end with an extension of .npy, this extension will be automatically added. arr: The array to be saved allow_pickle: Optional, a boolean value that allows the use of Python pickles to save object arrays. Python's pickle is used for serializing and deserializing objects before saving to disk files or before reading from disk files. fix_imports: Optional, for convenience of Pyhton2 from the file3 saved data.
 import numpy as np 
  
 a = np.array([1,2,3,4,5] 
  
 # Save to test.npy file
 np.save('test.npy',a) 
  
 # Save to test1.npy file, if there is no extension .npy at the end of the file path, this extension will be automatically added
 np.save('test1.npy',a)

We can view the contents of the file:

 $ cat test.npy 
 ?NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (5,),} 
 $ cat test1.npy 
 ?NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (5,),}

It can be seen that the file is garbled because it is the data after the Numpy-specific binary format.

We can use the load() function to read the data and display it normally:

import numpy as np 
b = np.load('test.npy') 
print(b)

The output result is:

[1 2 3 4 5]

np.savez

The numpy.savez() function saves multiple arrays to files with the npz extension.

numpy.savez(file, *args, **kwds)

Parameter description:

file: The file to be saved, with the extension .npz, if there is no extension at the end of the file path .npz, and this extension will be automatically added. args: The arrays to be saved can use keyword parameters to name the arrays, and arrays passed with non-keyword parameters will be automatically named arr_0, arr_1, … . kwds: The arrays to be saved use keyword names.
 import numpy as np
 a = np.array([1,2,3],[4,5,6])
 b = np.arange(0, 1.0, 0.1)
 c = np.sin(b)
 # c used keyword parameter sin_array
 np.savez("w3codebox.npz", a, b, sin_array = c)
 r = np.load("w3codebox.npz) 
 print(r.files) # View the names of each array
 print(r['arr_0']) # Array a
 print(r['arr_'])1']) # Array b
 print(r['sin_array']) # Array c

The output result is:

 ['sin_array', 'arr_0', 'arr_']1']
 [[1 2 3]
  [4 5 6]]
 [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
 [0. 0.09983342 0.19866933 0.29552021 0.38941834 0.47942554
  0.56464247 0.64421769 0.71735609 0.78332691]

savetxt()

The savetxt() function stores data in a simple text file format, corresponding to the use of loadtxt() function to retrieve data.

 np.loadtxt(FILENAME, dtype=int, delimiter=' ')
 np.savetxt(FILENAME, a, fmt="%d", delimiter=",")

The parameter delimiter can specify various delimiters, converter functions for specific columns, and the number of lines to be skipped, etc.

 import numpy as np
 a = np.array([1,2,3,4,5] 
 np.savetxt('out.txt',a) 
 b = np.loadtxt('out.txt') 
  
 print(b)

The output result is:

[1. 2. 3. 4. 5.]

Using delimiter parameter:

 import numpy as np
 a=np.arange(0,10,0.5).reshape(4,-1)
 np.savetxt("out.txt",a,fmt="%d",delimiter=",")  # save as integers, separated by commas
 b = np.loadtxt("out.txt",delimiter=",")  # load also specify as comma-separated
 print(b)
   [[0. 0. 1. 1. 2.]
  [2. 3. 3. 4. 4.]
  [5. 5. 6. 6. 7.]
  [7. 8. 8. 9. 9.]]