如何在python中与Fortran的“access=stream”等价

2024-09-29 01:27:36 发布

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

假设我在做一个循环,在每次迭代之后,y想要扩展一些数组。你知道吗

iter 1-------->;iter 2-------->;iter 3-------->;。。。。你知道吗

形状=[2,4]---->;形状=[2,12]---->;形状=[2,36]---->;。。。。你知道吗

在fortran中,我通常通过在二进制文件中添加新的数字来实现:

OPEN(2,file='array.in',form='unformatted',status='unknown',access='stream')
write(2) newarray

因此,这将在最后使用新值扩展旧数组。你知道吗

我希望在python中也这样做。这是我迄今为止的尝试:

import numpy as np

#write 2x2 array to binfile
bintest=open('binfile.in','wb')
np.ndarray.tofile(np.array([[1.0,2.0],[3.0,4.0]]),'binfile.in')
bintest.close()

#read array from binfile 
artest=np.fromfile('binfile.in',dtype=np.float64).reshape(2,2)

但我不能让它扩展数组。让我们说。。在结尾处出现另一个[[5.0,5.0],[5.0,5.0]]

#append new values.
np.ndarray.tofile(np.array([[5.0,5.0],[5.0,5.0]]),'binfile.in')

使其在读数后[[1.0,2.0,5.0,5.0],[3.0,4.0,5.0,5.0]]。 我该怎么做?你知道吗

我的另一个问题是,我希望能够在不知道最终数组的形状(我知道它将是2xn)的情况下实现这一点。但这并不重要。你知道吗

编辑:使用“access=stream”只是为了跳过读取格式头和尾的过程。你知道吗


Tags: ingtstreamaccessnp数组arraywrite
1条回答
网友
1楼 · 发布于 2024-09-29 01:27:36

这样做的诀窍:

import numpy as np

#write
bintest=open('binfile.in','ab')
a=np.array([[1.0,2.0],[3.0,2.0]])
a.tofile(bintest)
bintest.close()

#read
array=np.fromfile('binfile.in',dtype=np.float64)

这样,每次运行时,它都会将新数组追加到文件的末尾。你知道吗

相关问题 更多 >