我发现用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程序,读取这个二进制文件,然后保存我需要使用的数据?
发布于 2012-01-03 18:46:20
按如下方式读取二进制文件内容:
with open(fileName, mode='rb') as file: # b is important -> binary
fileContent = file.read()
然后使用struct.unpack“解压缩”二进制数据
起始字节:struct.unpack("iiiii", fileContent[:20])
body:忽略标题字节和尾部字节(= 24);剩下的部分构成body,为了知道body中的字节数,用4整除;得到的商乘以字符串'i'
,创建正确的unpack方法格式:
struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4])
结束字节:struct.unpack("i", fileContent[-4:])
发布于 2012-01-03 18:18:02
通常,我建议您考虑使用Python的struct模块来实现这一点。它是Python的标准,应该很容易将您的问题规范转换为适合struct.unpack()
的格式化字符串。
请注意,如果字段之间/周围有“看不见的”填充,您需要找出它并将其包含在unpack()
调用中,否则您将读取错误的位。
读取文件的内容以获得要解压缩的内容是相当简单的:
import struct
data = open("from_fortran.bin", "rb").read()
(eight, N) = struct.unpack("@II", data)
这将解压前两个字段,假设它们从文件的最开始处开始(没有填充或无关数据),并假定本机字节顺序( @
符号)。格式化字符串中的I
表示“无符号整数,32位”。
发布于 2012-01-03 18:41:29
您可以使用numpy.fromfile
,它可以从文本和二进制文件中读取数据。首先使用numpy.dtype
构造一个表示文件格式的数据类型,然后使用numpy.fromfile
从文件中读取该类型。
https://stackoverflow.com/questions/8710456
复制相似问题