我发现用 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 程序,读取这个二进制文件,然后保存我需要使用的数据?
原文由 Brian 发布,翻译遵循 CC BY-SA 4.0 许可协议
像这样读取二进制文件内容:
然后使用 struct.unpack “解压”二进制数据:
起始字节:
struct.unpack("iiiii", fileContent[:20])
正文:忽略标题字节和尾随字节 (= 24);剩下的部分组成body,要知道body中的字节数做整数除以4;获得的商乘以字符串
'i'
为 unpack 方法创建正确的格式:结束字节:
struct.unpack("i", fileContent[-4:])