0

我正在尝试使用 numpy fromfile 函数从 Python 中的二进制文件中读取非连续字段。它基于这个使用 fread 的 Matlab 代码:

    fseek(file, 0, 'bof');
    q = fread(file, inf, 'float32', 8);

8 表示读取每个值后我想跳过的字节数。我想知道 fromfile 中是否有类似的选项,或者是否有另一种从 Python 中的二进制文件中读取特定值的方法。谢谢你的帮助。

亨里克

4

1 回答 1

0

像这样的东西应该可以工作,未经测试:

import struct

floats = []
with open(filename, 'rb') as f:
    while True:
        buff = f.read(4)                # 'f' is 4-bytes wide
        if len(buff) < 4: break
        x = struct.unpack('f', buff)[0] # Convert buffer to float (get from returned tuple)
        floats.append(x)                # Add float to list (for example)
        f.seek(8, 1)                    # The second arg 1 specifies relative offset

使用struct.unpack()

于 2018-06-15T11:51:33.467 回答