NumPy ndarray.tofile()
The numpy.ndarray.tofile()
method writes an array to a file (or file-like object) in binary or text format. It provides a simple way to save NumPy arrays to disk for later retrieval.
Syntax
ndarray.tofile(fid, sep='', format='%s')
Parameters
Parameter | Type | Description |
---|---|---|
fid | str or file object | File name or file object where the data is written. |
sep | str, optional | String separator for text mode. If empty ('' ), writes in binary format. |
format | str, optional | Format string for text mode output, default is '%s' . |
Return Value
This method does not return any value. It writes the array directly to the specified file.
Examples
1. Writing a NumPy Array to a Binary File
In this example, we save a NumPy array to a binary file and later read it back.
import numpy as np
# Create a sample array
arr = np.array([1, 2, 3, 4, 5], dtype=np.int32)
# Save array to a binary file
arr.tofile('array_data.bin')
# Read the binary file and reconstruct the array
loaded_arr = np.fromfile('array_data.bin', dtype=np.int32)
print(loaded_arr) # Output: [1 2 3 4 5]
Output:
[1 2 3 4 5]
The data is saved in binary format without separators. We use np.fromfile()
to read the file and reconstruct the array.
2. Writing a NumPy Array to a Text File with a Separator
This example saves an array as a text file with comma-separated values.
import numpy as np
# Create a 2D NumPy array
arr = np.array([[10, 20, 30], [40, 50, 60]])
# Save the array as a CSV file
arr.tofile('array_data.csv', sep=',', format='%d')
# Read the CSV file back as a NumPy array
loaded_arr = np.loadtxt('array_data.csv', delimiter=',')
print(loaded_arr)
Output:
[[10. 20. 30.]
[40. 50. 60.]]
The array is saved as a text file with values separated by commas, and np.loadtxt()
is used to read the file back.
3. Writing a NumPy Array with a Custom Format
In this example, we save a floating-point array using a specific decimal precision format.
import numpy as np
# Create an array of floating-point numbers
arr = np.array([3.14159, 2.71828, 1.41421])
# Save array with formatted text output
arr.tofile('float_data.txt', sep=' ', format='%.2f')
# Read back the saved file
loaded_arr = np.loadtxt('float_data.txt')
print(loaded_arr)
Output:
[3.14 2.72 1.41]
The values are saved with two decimal places and space-separated. When read back, they are interpreted as floating-point numbers.