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

2024-03-29 13:07:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

亨里克


Tags: 文件函数代码选项二进制fileinfmatlab
1条回答
网友
1楼 · 发布于 2024-03-29 13:07:29

这样的方法应该有效,未经测试:

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

使用^{}

相关问题 更多 >