
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
Numpy fromfile() Function
The Numpy fromfile() function is used to read data from a binary or text file into a NumPy array. The function efficiently reads binary data with a known data type or parses simply formatted text files, depending on the mode specified. Data written using the numpy.tofile() method can typically be read back using this function, provided the data format matches.
Syntax
Following is the syntax of the Numpy fromfile() function −
numpy.fromfile(file, dtype=float, count=-1, sep='', offset=0, like=None)
Parameters
Following are the parameters of the Numpy fromfile() function −
- file: The file or file-like object to read. This can be a string representing the file path or an open file object.
- dtype(optional): The data type of the returned array. By default, it is set to float, but it can be specified as any NumPy dtype, such as int, float32, etc.
- count(optional): The number of items to read. If -1 (default), all items in the file will be read.
- sep(optional):The separator used if reading from a text file. An empty string ('') indicates binary mode. A string (e.g., a comma or space) indicates text mode.
- offset(optional): The offset (in bytes) from the files current position. By default offset is assigned to 0. Only permitted for binary files.
- like (optional): It allows the creation of an array which is like the input object but uses an existing array-like object (like another NumPy array).
Return Value
The function returns a NumPy array populated with the data read from the file.
Example
Following is a basic example to read binary data from a file using Numpy fromfile() function −
import numpy as np # Create a binary file for the example data = np.array([11, 22, 33, 44], dtype=np.int32) data.tofile('example_data.bin') # Now read the binary data using numpy.fromfile() read_data = np.fromfile('example_data.bin', dtype=np.int32) print("Binary Data:", read_data)
Output
Following is the output of the above code −
Binary Data: [11 22 33 44]
Example : Reading Text Data
In the following example, we read data from a text file into a NumPy array using the numpy.fromfile() function −
import numpy as np # Create a text file for the example with open('example_data.txt', 'w') as file: file.write('85 25 15 24 9') # reading the text data using numpy.fromfile() read_data = np.fromfile('example_data.txt', dtype=np.float64, sep=' ') print("Text Data:", read_data)
Output
Following is the output of the above code −
Text Data: [85. 25. 15. 24. 9.]
Example : Reading a Specific Number of Items
We can specify the count parameter to limit the number of items to read from the file. In the following example, we read only the first 4 elements from a binary file −
import numpy as np # Create a binary file for the example data = np.array([18, 80, 24, 99, 56, 45, 79, 31], dtype=np.int32) data.tofile('example_data.bin') # Read only the first 4 elements using numpy.fromfile() read_data = np.fromfile('example_data.bin', dtype=np.int32, count=4) print("Read First 4 Elements:", read_data)
Output
Following is the output of the above code −
Read First 4 Elements: [18 80 24 99]
Example : Binary vs. Text Mode
When the sep parameter is an empty string (sep=''), the file is read in binary mode. When sep is specified with a character (e.g., a space or comma), the file is read in text mode.
In the following example, we have demonstrated the difference between reading in binary mode and text mode using numpy.fromfile() −
import numpy as np # Write some binary data data = np.array([56, 29, 66, 89, 77], dtype=np.int32) data.tofile('binary_data.bin') # Read in binary mode binary_read = np.fromfile('binary_data.bin', dtype=np.int32) print("Read Binary Mode:", binary_read) # Write some text data with open('text_data.txt', 'w') as file: file.write('45, 77, 25, 19, 85, 96') # Read in text mode text_read = np.fromfile('text_data.txt', dtype=np.int32, sep=',') print("Read Text Mode:", text_read)
Output
Following is the output of the above code −
Read Binary Mode: [56 29 66 89 77] Read Text Mode: [45 77 25 19 85 96]