用python读取二进制文件

2024-04-19 15:48:42 发布

您现在位置: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程序,读取这个二进制文件,然后保存需要使用的数据?


Tags: 文件oftheidnumberreadbytes二进制
3条回答

您可以使用^{},它可以从文本和二进制文件中读取数据。首先使用^{}构造一个表示文件格式的数据类型,然后使用numpy.fromfile从文件中读取该类型。

一般来说,我建议您考虑使用Python的struct模块来实现这一点。它是Python的标准,应该很容易将问题的规范转换为适合于struct.unpack()的格式化字符串。

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

读取文件内容以便进行解包非常简单:

import struct

data = open("from_fortran.bin", "rb").read()

(eight, N) = struct.unpack("@II", data)

这将解压缩前两个字段,假设它们从文件的最开始处开始(没有填充或无关数据),并且还假设使用本机字节顺序(符号@)。格式化字符串中的I表示“无符号整数,32位”。

读取二进制文件内容,如下所示:

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

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

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

正文:忽略标题字节和尾随字节(=24);其余部分构成正文,以知道正文中的字节数做整数除以4;所得的商乘以字符串'i',以创建解包方法的正确格式:

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

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

相关问题 更多 >