【发布时间】:2013-04-22 13:43:51
【问题描述】:
假设我们有一个简单的小文件,其中包含一个包含不同值类型的一维数组,具有特定结构(第一项是 MATLAB uint,第二个值是 MATLABuint,其余值是 float )
如何在 Python 中从文件中读取这样一个异构类型的数组?
MATLAB 中的等效代码如下。
function M = load_float_matrix(fileName)
fid = fopen(fileName);
if fid < 0
error(['Error during opening the file ' fileName]);
end
rows = fread(fid, 1, 'uint');
cols = fread(fid, 1, 'uint');
data = fread(fid, inf, 'float');
M = reshape(data, [cols rows])';
fclose(fid);
end
注意:this thread 描述了以下读取三个连续 uint32 值的方法:
f = open(...)
import array
a = array.array("L") # L is the typecode for uint32
a.fromfile(f, 3)
但是,我怎么知道 L 是 uint32 的类型代码?那么其他类型呢? (例如float)。
另外,我如何从f 中读取连续值? a.fromfile 会向前移动文件中的读取指针吗?
【问题讨论】:
-
除非你有理由避免将 numpy 作为依赖项,否则 google numpy.loadtxt
标签: python matlab binaryfiles fread