Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Matlab 'fscanf' in Python?

The Matlab function fscanf() seems to be very powerful. Is there any equivalent of the same in python (or numpy)?

Specifically I want to read a matrix from file but I don't want to iterate through each line to read the matrix. Something of this sort (from matlab for reading a 2D 1000x1000 matrix):

matrix = fscanf(fopen('input.txt'),'%d',[1000,1000]); 
like image 966
Atul Goyal Avatar asked Mar 23 '11 08:03

Atul Goyal


1 Answers

Python has no built-in fscanf function. The closest way to do it is to read the file line by line and use regular expressions.

Numpy (the Matlab-like Python library), however, has a function that allows to read a file and construct an array from is content : numpy.fromfile (or, as suggested in the other answers, numpy.loadtxt may be more suitable in this case).

like image 82
Wookai Avatar answered Sep 20 '22 13:09

Wookai