阅读与Python二进制文件 [英] Reading a binary file with python
问题描述
我觉得特别难读的二进制文件与Python。你能帮我一下吗?
我需要阅读这个文件,这在Fortran 90中很容易被
I find particularly difficult reading binary file with Python. Can you give me a hand? I need to read this file, which in Fortran 90 is easily read by
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)
在详细地,文件格式是:
In detail, the file format is:
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的程序,阅读本二进制文件,然后保存,我需要使用数据的任何机会呢?
How can I read this with Python? I tried everything but it never worked. Is there any chance I might use a f90 program in python, reading this binary file and then save the data that I need to use?
推荐答案
阅读这样的二进制文件的内容:
Read the binary file content like this:
with open(fileName, mode='rb') as file: # b is important -> binary
fileContent = file.read()
然后选择解压使用二进制数据 struct.unpack :
起始字节: struct.unpack(IIIII,fileContent [20])
正文:忽略标题字节,尾随字节(= 24);剩余部分形成主体,要知道在体内由4做的整数除法的字节数;得到的商数由字符串乘以<$ C $ C>我以创建为解压方法的正确格式为:
The body: ignore the heading bytes and the trailing byte (= 24); The remaining part forms the body, to know the number of bytes in the body do an integer division by 4; The obtained quotient is multiplied by the string 'i'
to create the correct format for the unpack method:
struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4])
末字节: struct.unpack(I,fileContent [-4:])
这篇关于阅读与Python二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!