【发布时间】:2012-02-01 09:15:33
【问题描述】:
我发现用 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 程序,读取这个二进制文件,然后保存我需要使用的数据?
【问题讨论】:
-
这个文件是由 Fortran 程序编写的吗?如果是这样,它是如何写入的,因为默认情况下,Fortran 在它写入文件的每条记录之前添加额外的数据。读取数据时可能需要注意这一点。
-
请忽略我之前的评论,整数 8 和 4*N 显然是这个附加数据。
-
另外,请参阅问题的答案reading binary file in python。
-
Numpy 的
fromfile函数可以轻松读取二进制文件。我推荐它。 -
...并始终注意您的字节序,尤其是。在不同制造商的计算机之间移植时。