python二进制文件读写文件错误_在不知道结构的情况下使用python读取二进制文件...

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

I get as output:

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.

I would appreciate any kind of help :)

解决方案

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

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

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)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值