【问题标题】:How to skip bytes after reading data using numpy fromfile使用numpy fromfile读取数据后如何跳过字节
【发布时间】:2018-11-25 06:06:35
【问题描述】:

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

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

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

亨里克

【问题讨论】:

  • 你为什么需要 numpy 呢?只需open() 二进制模式下您的文件并使用read() and seek() 遍历您的文件。

标签: python numpy fread fromfile


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 2020-06-14
    • 2019-07-28
    相关资源
    最近更新 更多