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.
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
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.
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)
In the above code:
In the output, an array has been shown which contain elements present in the out_file.npy.
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)