如何在Python中从C语言创建的二进制文件中读取/写入浮点数值

3
我想从二进制文件中读取/写入C浮点数值,如果它是用C创建的?
文件是这样创建的:
#include <stdio.h>

int main() {
    const int NUMBEROFTESTELEMENTS = 10;
    /* Create the file */
    float x = 1.1;
    FILE *fh = fopen ("file.bin", "wb");
    if (fh != NULL) {
       for (int i = 0; i < NUMBEROFTESTELEMENTS; ++i)
       {
            x = 1.1*i;
            fwrite (&x,1, sizeof (x), fh);
            printf("%f\n", x);
       }
        fclose (fh);
    }

    return 0;
}

我发现了如下这种方法:(原文链接)

file=open("array.bin","rb")
number=list(file.read(3))
print (number)
file.close()

但这并不能保证读取的值是C浮点数。

array.bin里面是什么? - Abdul Niyas P M
@AbdulNiyasPM 我更新了问题,并附上了生成文件的代码。 - gabor aron
@mch也许我不知道这如何返回给我精确的值,你能否给我一个基于此的示例,那么我也可以接受它作为答案。 - gabor aron
2个回答

3
import struct
with open("array.bin","rb") as file:
    numbers = struct.unpack('f'*10, file.read(4*10))
print (numbers)

这应该就可以了。 "numbers" 是一个包含10个值的元组。

1
如果您关心性能,我建议使用numpy.fromfile来读取浮点值:
import numpy as np

class FloatReader:
    def __init__(self, filename):
        self.f = open(filename, "rb")
    
    def read_floats(self, count : int):
        return np.fromfile(self.f, dtype=np.float32, count=count, sep='')

从性能角度来看,这种方法比struct.unpack快得多!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接