繁体   English   中英

如何使用numpy fromfile读取数据后跳过字节

[英]How to skip bytes after reading data using numpy fromfile

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

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

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

亨里克

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM