numpy.fromfile#
- numpy.fromfile(file,dtype=float,count=-1,sep='',offset=0,*,like=None)#
Construct an array from data in a text or binary file.
A highly efficient way of reading binary data with a known data-type,as well as parsing simply formatted text files. Data written using thetofile method can be read using this function.
- Parameters:
- filefile or str or Path
Open file object or filename.
- dtypedata-type
Data type of the returned array.For binary files, it is used to determine the size and byte-orderof the items in the file.Most builtin numeric types are supported and extension types may be supported.
- countint
Number of items to read.
-1means all items (i.e., the completefile).- sepstr
Separator between items if file is a text file.Empty (“”) separator means the file should be treated as binary.Spaces (” “) in the separator match zero or more whitespace characters.A separator consisting only of spaces must match at least onewhitespace.
- offsetint
The offset (in bytes) from the file’s current position. Defaults to 0.Only permitted for binary files.
- likearray_like, optional
Reference object to allow the creation of arrays which are notNumPy arrays. If an array-like passed in as
likesupportsthe__array_function__protocol, the result will be definedby it. In this case, it ensures the creation of an array objectcompatible with that passed in via this argument.New in version 1.20.0.
See also
load,savendarray.tofileloadtxtMore flexible way of loading data from a text file.
Notes
Do not rely on the combination oftofile and
fromfilefordata storage, as the binary files generated are not platformindependent. In particular, no byte-order or data-type information issaved. Data can be stored in the platform independent.npyformatusingsaveandloadinstead.Examples
Construct an ndarray:
>>>importnumpyasnp>>>dt=np.dtype([('time',[('min',np.int64),('sec',np.int64)]),...('temp',float)])>>>x=np.zeros((1,),dtype=dt)>>>x['time']['min']=10;x['temp']=98.25>>>xarray([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
Save the raw data to disk:
>>>importtempfile>>>fname=tempfile.mkstemp()[1]>>>x.tofile(fname)
Read the raw data from disk:
>>>np.fromfile(fname,dtype=dt)array([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
The recommended way to store and load data:
>>>np.save(fname,x)>>>np.load(fname+'.npy')array([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])