用python读取二进制文件

我发现使用Python阅读二进制文件特别困难。 你能帮我一下吗? 我需要阅读这个文件,这在Fortran 90中很容易阅读

int*4 n_particles, n_groups real*4 group_id(n_particles) read (*) n_particles, n_groups read (*) (group_id(j),j=1,n_particles) 

具体来说,文件格式是:

 Bytes 1-4 -- The integer 8. Bytes 5-8 -- The number of particles, N. Bytes 9-12 -- The number of groups. Bytes 13-16 -- The integer 8. Bytes 17-20 -- The integer 4*N. Next many bytes -- The group ID numbers for all the particles. Last 4 bytes -- The integer 4*N. 

我怎样才能阅读这与Python? 我尝试了一切,但它从来没有工作。 有没有机会在python中使用f90程序,读取这个二进制文件,然后保存我需要使用的数据?

像这样读取二进制文件内容:

 with open(fileName, mode='rb') as file: # b is important -> binary fileContent = file.read() 

然后使用struct.unpack “解压缩”二进制数据:

起始字节: struct.unpack("iiiii", fileContent[:20])

正文:忽略标题字节和尾随字节(= 24); 剩下的部分形成体,知道体内的字节数做一个整数除4; 获得的商与string'i'相乘,为解包方法创build正确的格式:

 struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4]) 

结束字节: struct.unpack("i", fileContent[-4:])

一般来说,我build议你看看使用Python的结构模块。 它是Python的标准,应该很容易将你的问题的规范翻译成适合于struct.unpack()的格式化string。

请注意,如果字段之间/周围存在“不可见的”填充,则需要弄清楚并将其包含在unpack()调用中,否则您将读取错误的位。

阅读文件的内容,以便有一些解压缩是非常微不足道的:

 import struct data = open("from_fortran.bin", "rb").read() (eight, N) = struct.unpack("@II", data) 

这将解压前两个字段,假定它们从文件的最开始(不填充或无关的数据)开始,并假定本地字节顺序( @符号)。 格式化string中的I表示“无符号整数,32位”。

你可以使用numpy.fromfile ,它可以从文本和二进制文件中读取数据。 您将首先使用numpy.dtype构造一个表示您的文件格式的数据types,然后使用numpy.fromfile从文件读取此types。