w3resource

NumPy Input and Output: ndarray.tofile() function

numpy.ndarray.tofile() function

The ndarray.tofile() function is used to write array to a file as text or binary (default).

Data is always written in 'C' order, independent of the order of a.

Syntax:

ndarray.tofile(fid, sep="", format="%s")

Version: 1.15.0

Parameter:

Name Description Required /
Optional
fid An open file object, or a string containing a filename.
file or str
Required
sep Separator between array items for text output. If "" (empty), a binary file is written, equivalent to file.write(a.tobytes()).
str
Required
format Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using "format" % item.
str
Required

Notes:
This is a convenience function for quick storage of array data.
Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness.
Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.

When fid is a file object, array contents are directly written to the file, bypassing the file object's write method.
As a result, tofile cannot be used with files objects supporting compression (e.g., GzipFile) or file-like objects that do not support fileno() (e.g., BytesIO).

NumPy.fromstring() method Example:

>>> import numpy as np
>>> np.array([1,300],np.int32).tofile('test1')
>>> with open('test1','rb') as x: print(x.read())  

Output:

 b'\x01\x00\x00\x00,\x01\x00\x00'

Python - NumPy Code Editor:

Previous: fromstring() function
Next: ndarray.tolist() function



Follow us on Facebook and Twitter for latest update.