numpy.save() in Python

The numpy module of Python provides a function called numpy.save() to save an array into a binary file in .npy format. In many of the cases, we require data in binary format to manipulate it.

Syntax:

snippet
numpy.save(file, arr, allow_pickle=True, fix_imports=True)

Parameters:

file: str, file, or pathlib.path

This parameter defines the file or filename in which the data is going to be saved. If this parameter is an object of a file, the filename will be unchanged. If the file parameter is a path or a string, the .npy extension will be added to the file name, and it will be done when it doesn't have one.

allow_pickle : bool(optional)

This parameter is used to allow the saving of objects into the pickle. The security and the probability are the reason for disallowing pickles.

fix_imports : bool(optional)

If fix_imports is set to True, then pickle does the mapping of the new Python3 names to the old module names, which are used in Python2. This makes the pickle data stream readable with Python2.

Example 1:

snippet
import numpy as np
from tempfile import TemporaryFile
out_file = TemporaryFile()
x=np.arange(15)
np.save(out_file, x)
_=out_file.seek(0) # Only needed here to simulate closing & reopening file
np.load(outfile)

Output:

Output
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

In the above code:

  • We have imported numpy with alias name np.
  • We have also imported TemporaryFile from tempfile.
  • We have created an object out_file of TemporaryFile.
  • We have created an array 'x' using arange() function.
  • We have saved the array's elements as binary in npy file using np.save() function.
  • We have passed the array 'x' and filename in the function.
  • We have closed and reopened the file using seek(0) function.
  • Lastly, we tried to load the out_file.

In the output, an array has been shown which contain elements present in the out_file.npy.

Example 2:

snippet
import numpy as np
from tempfile import TemporaryFile
outfile = TemporaryFile()
x=np.arange(15)
np.save(outfile, x, allow_pickle=False)
_=outfile.seek(0) # Only needed here to simulate closing & reopening file
np.load(outfile)

Output:

Output
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +