与IDL方法相比,使用Python中的unpack读取二进制文件

问题描述 投票:1回答:1

我有一个读取二进制文件的IDL过程,我尝试将其转换为Python例程。 IDL代码如下所示:

a = uint(0)
b = float(0)
c = float(0)
d = float(0)
e = float(0)
x=dblarr(nptx)
y=dblarr(npty)
z=dblarr(nptz)
openr,11,name_file_data,/f77_unformatted
readu,11,a
readu,11,b,c,d,e
readu,11,x
readu,11,y
readu,11,z

它完美地运作。所以我在python中编写相同的东西,但我找不到相同的结果(即使'a'的值不同)。这是我的代码:

x=np.zeros(nptx,float)
y=np.zeros(npty,float)
z=np.zeros(nptz,float)
with open(name_file_data, "rb") as fb:
    a, = struct.unpack("I", fb.read(4))
    b,c,d,e = struct.unpack("ffff", fb.read(16))
    x[:] = struct.unpack(str(nptx)+"d", fb.read(nptx*8))[:]
    y[:] = struct.unpack(str(npty)+"d", fb.read(npty*8))[:]
    z[:] = struct.unpack(str(nptz)+"d", fb.read(nptz*8))[:]

希望它能帮助任何人回答我。

更新:正如答案中所建议的那样,我现在正在尝试使用“FortranFile”模块,但我不确定我是否理解了它的使用方法。

from scipy.io import FortranFile
f=FortranFile(name_file_data, 'r')
a=f.read_record('H')
b=f.read_record('f','f','f','f')

但是,我没有得到'a'的整数,而是得到:array([0,0],dtype = uint16)。

我对'b'有以下错误:获得的大小(1107201884)不是给出的dtypes的倍数(16)

python numpy binary idl-programming-language
1个回答
1
投票

根据a table of IDL data typesUINT(0)创建一个16位整数(即两个字节)。在Python struct module中,I format character表示4字节整数,H表示无符号16位整数。

尝试更改解压缩a的行

    a, = struct.unpack("H", fb.read(2))

不幸的是,这可能无法解决问题。您使用/f77_unformatted选项与openr,这意味着该文件不仅包含变量的原始字节。 (有关documentation of the OPENR command的更多信息,请参阅/f77_unformatted。)

您可以尝试使用qazxsw poi来读取文件,但不能保证它会起作用。未格式化的Fortran文件的二进制布局取决于编译器。

© www.soinside.com 2019 - 2024. All rights reserved.