0
0
SciPydata~5 mins

Saving and loading data (scipy.io)

Choose your learning style9 modes available
Introduction

We save data to keep it safe and use it later. Loading data helps us continue work without starting over.

You want to save results of a calculation to use later.
You need to share data with a teammate in a file.
You want to load data from a previous session to analyze again.
You want to save arrays or matrices in a file format that Python can read easily.
You want to store data in a format compatible with MATLAB.
Syntax
SciPy
from scipy import io

# Save data to a .mat file
io.savemat('filename.mat', {'var_name': data})

# Load data from a .mat file
data = io.loadmat('filename.mat')

The data is saved in MATLAB .mat file format.

Data is stored as a dictionary with variable names as keys.

Examples
This saves a numpy array named 'array' into 'mydata.mat'.
SciPy
from scipy import io
import numpy as np

arr = np.array([1, 2, 3])
io.savemat('mydata.mat', {'array': arr})
This loads the file and prints the saved array.
SciPy
from scipy import io

loaded = io.loadmat('mydata.mat')
print(loaded['array'])
Sample Program

This program saves a 2x2 matrix to a file and then loads it back to print it.

SciPy
from scipy import io
import numpy as np

# Create some data
matrix = np.array([[10, 20], [30, 40]])

# Save the matrix to a file
io.savemat('matrix_data.mat', {'matrix': matrix})

# Load the data back
loaded_data = io.loadmat('matrix_data.mat')

# Print the loaded matrix
print(loaded_data['matrix'])
OutputSuccess
Important Notes

When loading, the result is a dictionary with extra metadata keys like '__header__'.

Use the variable name keys to access your saved data.

Files saved with savemat can be opened in MATLAB software.

Summary

Use io.savemat to save data as .mat files.

Use io.loadmat to load data back into Python.

Data is stored and accessed as dictionary entries by variable names.