BetterDocs
Home
Docs

Creation | np.fromfile()

Method:

np.fromfile(file, dtype=np.float64, count=-1, sep='', offset=0, *, like=None)

Reads an array from a binary or text file.

Returns:

np.ndarray

Parameters:

file: filepath-

File to read from.

import numpy as np

# Write to a file with a specified dtype
np.array([1, 2, 3], dtype=np.int32).tofile('data.bin')

# Read from the file with the same dtype
arr_from_file = np.fromfile(file='data.bin', dtype=np.int32)
print(arr_from_file)  # Output: [1 2 3]

.tofile()  method writes an array to a file in a binary or text format.

The dtype must be specified explicitly unless the file's data-type is np.float64.

dtype: data-type, Optional-

Specifies the data-type of the array elements.

import numpy as np

# Write to a file with a specified dtype
np.array([1., 2., 3.]).tofile('data.bin')

# Read from the file with the same dtype
arr_from_file = np.fromfile('data.bin')
print(arr_from_file)  # Output: [1. 2. 3.]

Values: +

count: int, Optional-

Number of items to read.

import numpy as np

# Write to a file with a specified dtype
np.array([1., 2., 3.]).tofile('data.bin')

# Read from the file with the same dtype
arr_from_file = np.fromfile('data.bin', count=2)
print(arr_from_file)  # Output: [1. 2.]

sep: str, Optional-

Delimiter for text files.

import numpy as np

arr = np.array([1, 2, 3])
arr.tofile(file='data.txt', sep=",")  # Write as text
arr_from_file = np.fromfile(file='data.txt', sep=",")  # Read as text
print(arr_from_file)  # Output: [1. 2. 3.]

offset: int, Optional-

Start position in the file.

import numpy as np

# Data to write
data = np.array([10, 20, 30, 40, 50], dtype=np.int32)

# Write the data to a binary file
with open('data_with_header.bin', 'wb') as f:
    f.write(b'BETTER')  # Write a header (6 bytes)
    data.tofile(f)      # Write the actual data

# Read the file, skipping the 6-byte header
arr = np.fromfile('data_with_header.bin', dtype=np.int32, offset=6)
print(arr)
# Output: [10 20 30 40 50]

like: None, Optional-

The like parameter in np.fromfile() was introduced to make array creation more flexible, particularly for compatibility with libraries that extend NumPy, like Dask, CuPy, or other libraries that create arrays compatible with np.ndarray but optimized for different backends (e.g., parallel processing or GPU-based arrays).


Logo

BetterDocs

Support

EmailDiscordForms

Documentations

Python

Company

AboutDocs

Policies

Terms of ServicePrivacy Policy