Create an array using files in numpy with numpy.fromfile() function

Spread the love

In this tutorial, you will learn how to create an array using files in numpy with numpy.fromfile() function.

Syntax:numpy.fromfile(file, dtype=float, count=-1, sep=”)
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 the tofile method can be read using this function.

file : file or str
Open file object or filename.

dtype : data-type
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.

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

sep : str
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.

#creation of file array
dt = np.dtype([('time', [('min', int), ('sec', int)]), ('temp', float)])
x = np.zeros((1,), dtype=dt)
x['time']['min'] = 10; x['temp'] = 98.25
#load file
import numpy as np
import os
fname = os.tmpnam()
#The recommended way to store and load data:, x)
np.load(fname + '.npy')




Leave a Reply

Your email address will not be published. Required fields are marked *