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

原文由 Brian 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 523
2 个回答

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

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

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

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

正文:忽略标题字节和尾随字节 (= 24);剩下的部分组成body,要知道body中的字节数做整数除以4;获得的商乘以字符串 'i' 为 unpack 方法创建正确的格式:

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

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

原文由 gecco 发布,翻译遵循 CC BY-SA 3.0 许可协议

通常,我会建议您为此使用 Python 的 结构 模块。它是 Python 的标准,应该很容易将您的问题规范转换为适合 struct.unpack() 的格式字符串。

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

读取文件的内容以解压一些东西是非常简单的:

 import struct

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

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

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

原文由 unwind 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题