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

The Matlab fscanf() function seems very powerful. Is there any equivalent in python (or numpy)?

In particular, I want to read the matrix from a file, but I do not want to iterate over each row to read the matrix. Something like that (from Matlab to read a 1000x1000 2D matrix):

 matrix = fscanf(fopen('input.txt'),'%d',[1000,1000]); 
+4
source share
5 answers

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

Numpy (a library similar to Matlab-like Python), however, has a function that allows you to read a file and build an array from content: numpy.fromfile (or, as suggested in other answers, numpy.loadtxt might be more appropriate in this case).

+5
source

I'm sure not, but repetition is not too difficult. This would do it:

 matrix = [] for i in open('input.txt'): matrix.append( map(int, i.split()) ) 

If you need something more complex (i.e. not just ints separated by single characters), regular expressions can be a way.

+3
source

I think the Wukai answer is incorrect. I think numpy.loadtxt is what you are looking for.

+1
source

Have you looked at numpy? - http://www.scipy.org/Download

By the way, fscanf internally saves data in column order. Therefore, I do not think that there will be any gain in efficiency. http://www.mathworks.com/help/techdoc/ref/fscanf.html

0
source

I think the pythonic way to do this is to open the file and read the data in list from list using lists.

(I use data from a string for clarity and read it as if from a file using StringIO .)

 >>> from cStringIO import StringIO >>> data_file="1 2 3 4 5 6\n7 8 9 10 11 12\n13 14 15 16 17 18\n19 20 21 22 23 24\n" >>> reader=StringIO(data_file) >>> array=[map(int, reader.readline().split()) for i in xrange(4)] >>> array [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24]] 

As the earlier answer is mentioned, numpy has a more direct method.

0
source

Source: https://habr.com/ru/post/1344891/


All Articles