bundles / numpy 2.5.0.dev0+git20251130.2de293a / numpy / fromfile
built-in
numpy:fromfile
Signature
fromfile ( file , dtype = <class 'float'> , count = -1 , sep = '' , offset = 0 , * , like = None ) Summary
Construct an array from data in a text or binary file.
Extended Summary
A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the tofile method can be read using this function.
Parameters
file: file or str or PathAn open file object, a string containing the filename, or a Path object. When reading from a file object it must support random access (i.e. it must have tell and seek methods).
dtype: data-typeData type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file. Most builtin numeric types are supported and extension types may be supported.
count: intNumber of items to read.
-1means all items (i.e., the complete file).sep: strSeparator 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 one whitespace.
offset: intThe offset (in bytes) from the file's current position. Defaults to 0. Only permitted for binary files.
like: array_like, optionalReference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as
likesupports the__array_function__protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
Notes
Do not rely on the combination of tofile and fromfile for data storage, as the binary files generated are not platform independent. In particular, no byte-order or data-type information is saved. Data can be stored in the platform independent .npy format using save and load instead.
Examples
Construct an ndarray:import numpy as np 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 x✓
import tempfile fname = tempfile.mkstemp()[1] x.tofile(fname)✓
np.fromfile(fname, dtype=dt)
✓np.save(fname, x) np.load(fname + '.npy')✓
See also
- load
- loadtxt
More flexible way of loading data from a text file.
- ndarray.tofile
- save
Aliases
-
numpy.fromfile