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 1000×1000 matrix):
matrix = fscanf(fopen('input.txt'),'%d',[1000,1000]);
Python has no built-in
fscanffunction. 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.loadtxtmay be more suitable in this case).