问题描述
Matlab函数fscanf()
似乎非常强大. python(或numpy)中是否有相同的东西?
The Matlab function fscanf()
seems to be very powerful. Is there any equivalent of the same in python (or numpy)?
具体来说,我想从文件中读取矩阵,但是我不想遍历每一行以读取矩阵.这种东西(从matlab读取2D 1000x1000矩阵):
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没有内置的fscanf
函数.最接近的方法是逐行读取文件并使用正则表达式.
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 (类似于Matlab的Python库)具有允许读取文件的功能.并从is内容构造一个数组: numpy.fromfile
(或根据其他答案的建议, numpy.loadtxt
在这种情况下可能更合适.)
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).
这篇关于Python中的Matlab'fscanf'等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!