在python中简单阅读Fortran二进制数据并不那么简单 [英] simple reading of fortran binary data not so simple in python

查看:322
本文介绍了在python中简单阅读Fortran二进制数据并不那么简单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个FORTRAN代码的二进制输出文件。想在Python中阅读它。 (用FORTRAN读取并输出文本以读取python不是一种选择,长话短说)我可以简单地阅读第一条记录:

I have a binary output file from a FORTRAN code. Want to read it in python. (Reading with FORTRAN and outputting text to read for python is not an option. Long story.) I can read the first record in a simplistic manner:

>>> binfile=open('myfile','rb')
>>> pad1=struct.unpack('i',binfile.read(4))[0]
>>> ver=struct.unpack('d',binfile.read(8))[0]
>>> pad2=struct.unpack('i',binfile.read(4))[0]
>>> pad1,ver,pad2
(8,3.13,8)

没问题。但这是一个很大的文件,我需要更有效地做到这一点。所以我试试:

Just fine. But this is a big file and I need to do this more efficiently. So I try:

>>> (pad1,ver,pad2)=struct.unpack('idi',binfile.read(16))



<这不会运行。给我一个错误,并告诉我,解包需要长度为20的参数。自从上次检查4 + 8 + 4 = 16以来,这对我来说没有意义。当我放弃并用20替换16时,它会运行,但是这三个数字填充了数字垃圾。有没有人看到我在做什么错了?感谢!

This won't run. Gives me an error and tells me that unpack needs an argument with a length of 20. This makes no sense to me since the last time I checked, 4+8+4=16. When I give in and replace the 16 with 20, it runs, but the three numbers are populated with numerical junk. Does anyone see what I am doing wrong? Thanks!

推荐答案

您获得的大小是由于对齐,尝试 struct.calcsize('idi' )验证对齐后的大小实际上是20。要使用没有对齐的本地字节顺序,请指定 struct.calcsize('= idi')并将其应用于您的示例。

The size you get is due to alignment, try struct.calcsize('idi') to verify the size is actually 20 after alignment. To use the native byte-order without alignment, specify struct.calcsize('=idi') and adapt it to your example.

有关 struct 模块的更多信息,请查看 http://docs.python.org/2/library/struct.html

For more info on the struct module, check http://docs.python.org/2/library/struct.html

这篇关于在python中简单阅读Fortran二进制数据并不那么简单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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