SciPy - read() Function



The read function takes simple binary files and reads the data into Python so it can be manipulated or analyzed.

Syntax

The syntax for the SciPy read() method is as follows −

.read(filename, mmap=None)

Parameters

This method accepts the following parameters −

  • filename − The name of the file to be read.

  • mmap − The mmap parameter enables memory mapping for efficient file access, especially for large files, by loading only required portions into memory. By default (mmap=None), the entire file is loaded into memory.

Return Value

The method returns the contents of the file in a structured format (e.g., arrays or dictionaries), depending on the file type and its contents.

Example 1

This code generates a simple binary file named datafile.dat and then reads it back with the read method, showing its contents as a string.

import scipy.io

# Create a binary data file
with open("datafile.dat", "wb") as f:
    f.write(b"This is a test.")

# Read the binary file using read()
with open("datafile.dat", "rb") as f:
    data = f.read()

print("Read Data:", data.decode())

When we run above program, it produces following result

Read Data: This is a test.

Example 2

import numpy as np

# Create a large data file
large_data = np.random.rand(1000000)
np.save("largefile.npy", large_data)

# Read the large file using memory mapping
mapped_data = np.read("largefile.npy", mmap_mode="r")

print("First 5 elements:", mapped_data[:5])

Following is an output of the above code

First 5 elements: [0.13633589 0.64622249 0.5389321  0.66024416 0.42551346]
scipy_input_output.htm
Advertisements