【问题标题】:Matlab -> Python. Reading heterogeneous 1D binary array from diskMatlab -> Python。从磁盘读取异构一维二进制数组
【发布时间】: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


【解决方案1】:

试试 numpy。

下面是一种方法。

import numpy as np
f = open(filename,"r")
N = np.fromfile(fp,dtype=np.int32,count=2)
a = np.fromfile(fp,dtype=np.float64)
a = np.resize(a,N)

您还可以读取混合格式/类型(文本 + 二进制)文件。可以通过正确格式化 dtype 选项来组合第 3 行和第 4 行,google 以获得更多示例。

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2012-05-21
    • 2019-01-11
    • 2016-05-02
    • 2016-08-26
    相关资源
    最近更新 更多