在不知道结构的情况下使用python读取二进制文件 [英] Reading binary file with python without knowing structure

查看:182
本文介绍了在不知道结构的情况下使用python读取二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制文件,其中包含8000个粒子的位置. 我知道每个粒子值都应该看起来像"-24.6151 ..."(我不知道程序以何种精度给出这些值.我猜它是双精度(?).

I have a binary file containing the position of 8000 particles. I know that each particle value should look like "-24.6151..." (I don't know with which precision the values are given by my program. I guess it is double precision(?).

但是当我尝试使用以下代码读取文件时:

But when I try to read the file with this code:

In: with open('.//results0epsilon/energybinary/energy_00004.dat', 'br') as f:
    buffer = f.read()
    print ("Lenght of buffer is %d" % len(buffer))

    for i in buffer:
        print(int(i))

我得到输出:

Lenght of buffer is 64000

10

168

179

43
...

我跳过了整个值列表,但是正如您所看到的那样,这些值与我期望的值相去甚远.我想我有某种解码错误.

I skip the whole list of values but as you can see those values are far away from what I expect. I think I have some kind of decoding error.

我将不胜感激:)

推荐答案

您现在要打印的是bytes组成您的浮点数据.因此,将其作为数值没有意义.

What you are printing now are the bytes composing your floating point data. So it doesn't make sense as numerical values.

当然,由于我们没有看到您的数据,所以没有100%肯定的答案,但是我会尝试猜测:

Of course, there's no 100% sure answer since we didn't see your data, but I'll try to guess:

您要读取8000个值,文件大小为64000.因此,您可能具有double IEEE值(每个8个字节).如果不是 IEEE,那么您就敬酒了.

You have 8000 values to read and the file size is 64000. So you probably have double IEEE values (8 bytes each). If it's not IEEE, then you're toast.

在这种情况下,您可以尝试以下操作:

In that case you could try the following:

import struct
with open('.//results0epsilon/energybinary/energy_00004.dat', 'br') as f:
    buffer = f.read()
    print ("Length of buffer is %d" % len(buffer))

    data = struct.unpack("=8000d",buffer)

如果数据打印为伪造,则可能是字节顺序问题.因此,将=8000更改为<8000>8000.

if the data is printed bogus, it's probably an endianness problem. So change the =8000 by <8000 or >8000.

以获取参考和打包/解压缩格式: https://docs.python.org /3/library/struct.html

for reference and packing/unpacking formats: https://docs.python.org/3/library/struct.html

这篇关于在不知道结构的情况下使用python读取二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆