简体   繁体   English

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

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

I'm trying to read noncontiguous fields from a binary file in Python using numpy fromfile function. 我正在尝试使用numpy fromfile函数从Python中的二进制文件读取不连续的字段。 It's based on this Matlab code using fread: 它基于使用fread的Matlab代码:

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

8 indicates the number of bytes I want to skip after reading each value. 8表示读取每个值后要跳过的字节数。 I was wondering if there was a similar option in fromfile, or if there is another way of reading specific values from a binary file in Python. 我想知道fromfile中是否有类似的选项,或者是否存在另一种从Python二进制文件中读取特定值的方法。 Thanks for your help. 谢谢你的帮助。

Henrik 亨里克

Something like this should work, untested: 像这样的东西应该可以工作,未经测试:

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

Using struct.unpack() 使用struct.unpack()

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

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