读取Fortran二进制文件(流式访问)使用np.fromfile或open和stru

2024-09-26 22:53:47 发布

您现在位置:Python中文网/ 问答频道 /正文

以下Fortran代码:

INTEGER*2 :: i, Array_A(32)
Array_A(:) = (/ (i, i=0, 31) /)

OPEN (unit=11, file = 'binary2.dat', form='unformatted', access='stream')
    Do i=1,32
        WRITE(11) Array_A(i)
    End Do 
CLOSE (11)

产生以整数16位表示的从0到31的流式二进制输出。每个记录占用2个字节,因此它们被写入字节1、3、5、7,依此类推。access='stream'为每个记录取消Fortran的标准标头(我需要这样做以使文件尽可能小)。在

用十六进制编辑器查看,我得到:

^{pr2}$

尽管我的例子中,小数是绝对不好用的。在

现在我需要将这些二进制文件导入到Python2.7中,但我做不到。我尝试了许多不同的例程,但总是失败。在

1。尝试:“np.fromfile文件““

with open("binary2.dat", 'r') as f:
    content = np.fromfile(f, dtype=np.int16)

退货

[    0     1     2     3     4     5     6     7     8     9    10    11
    12    13    14    15    16    17    18    19    20    21    22    23
    24    25     0     0 26104  1242     0     0]

2。尝试:“结构”

import struct
with open("binary2.dat", 'r') as f:
    content = f.readlines()
    struct.unpack('h' * 32, content)

交付

struct.error: unpack requires a string argument of length 64

因为

print content
['\x00\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00\x07\x00\x08\x00\t\x00\n', '\x00\x0b\x00\x0c\x00\r\x00\x0e\x00\x0f\x00\x10\x00\x11\x00\x12\x00\x13\x00\x14\x00\x15\x00\x16\x00\x17\x00\x18\x00\x19\x00']

(注意定界符、t和n,根据Fortran的“流式处理”访问的作用,它们不应该存在)

3。尝试:“FortranFile”

f = FortranFile("D:/Fortran/Sandbox/binary2.dat", 'r')
print(f.read_ints(dtype=np.int16))

出现错误时:

TypeError: only length-1 arrays can be converted to Python scalars

(还记得它是如何在文件中间检测到分隔符的,但对于没有换行符的较短文件(例如从0到8的小数),它也会崩溃)

一些额外的想法:

Python在读取部分二进制文件时似乎遇到了问题。对于np.fromfile,它读取Hex 19(12月25日),但对于{}(12月26日)则崩溃。它似乎和字母混淆了,虽然0A,0B。。。工作很好。在

对于尝试2,content-结果很奇怪。小数点0到8很好,但是还有一个奇怪的现象。那么hex 09是什么意思?在

我花了好几个小时试图找出其中的逻辑,但我被卡住了,真的需要一些帮助。有什么想法吗?在


Tags: 文件streamaccessnp二进制流式contentarray
1条回答
网友
1楼 · 发布于 2024-09-26 22:53:47

问题出在打开文件模式下。默认为“文本”。将此模式更改为二进制:

with open("binary2.dat", 'rb') as f:
    content = np.fromfile(f, dtype=np.int16)

所有的数字都会被读取成功。有关更多详细信息,请参阅Python章节Binary Files。在

相关问题 更多 >

    热门问题