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]);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With