nlcpy.fromfile

nlcpy.fromfile(file, dtype=<class 'float'>, count=-1, sep='', offset=0)[source]

Constructs 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 the tofile method can be read using this function.

Parameters
filefile or str or pathlib.Path

Open file object or filename.

dtypedtype, optional

Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file.

countint, optional

Number of items to read. -1 means all items (i.e., the complete file).

sepstr, optional

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 one whitespace.

offsetint, optional

The offset (in bytes) from the file’s current position. Defaults to 0. Only permitted for binary files.

Returns
outndarray

Data read from the file.

See also

loadtxt

Loads data from a text file.

load

Loads arrays or pickled objects from .npy, .npz or pickled files.

Note

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

>>> import numpy as np
>>> import nlcpy as vp

Construct an ndarray:

>>> x = np.random.uniform(0, 1, 5)
>>> x  
array([0.61878546, 0.87721538, 0.92901071, 0.87754926, 0.07167856]) # random

Save the raw data to disk:

>>> import tempfile
>>> fname = tempfile.mkstemp()[1]
>>> x.tofile(fname)

Read the raw data from disk:

>>> vp.fromfile(fname)   
array([0.61878546, 0.87721538, 0.92901071, 0.87754926, 0.07167856]) # random

The recommended way to store and load data:

>>> np.save(fname, x)
>>> vp.load(fname + '.npy')  
array([0.61878546, 0.87721538, 0.92901071, 0.87754926, 0.07167856]) # random