SciPy input and output

SciPy Input and Output

The Scipy.io (input and output) package provides a large number of functions for working with files in various formats. Some of these formats are −

  • Matlab
  • IDL
  • Matrix Market
  • Wave
  • Arff
  • Netcdf, etc.

Let’s discuss the most commonly used file formats in detail:

MATLAB

The following are functions for loading and saving .mat files.

Number Function and Description
1 loadmat Loads a MATLAB file
2 savemat Saves a MATLAB file
3 whosmat Lists the variables in a MATLAB file

Let’s consider the following example.

import scipy.io as sio
import numpy as np

#Save a mat file
vect = np.arange(10)
sio.savemat('array.mat', {'vect':vect})

#Now Load the File
mat_file_content = sio.loadmat('array.mat')
Print mat_file_content

The above program will produce the following output.

{
   'vect': array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]), '__version__': '1.0',
   '__header__': 'MATLAB 5.0 MAT-file Platform: posix, Created on: Sat Sep 30
   09:49:32 2017', '__globals__': []
}

We can see the array and metadata. If we want to examine the contents of a MATLAB file without reading the data into memory, we can use the whosmat command as shown below.

import scipy.io as sio
mat_file_content = sio.whosmat('array.mat')
print mat_file_content

The above program will produce the following output.

[('vect', (1, 10), 'int64')]

Leave a Reply

Your email address will not be published. Required fields are marked *