繁体   English   中英

如何在python中使Fortran的'access = stream'等效

[英]How to make an equivalent to Fortran's 'access=stream' in 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]]。 我怎样才能做到这一点?

我遇到的另一个问题是,我希望能够在不知道最终数组的形状的情况下进行此操作(我知道它将是2 xn)。 但这不是那么重要。

编辑:“ access = stream”的使用只是跳过必须阅读格式标题和尾部的操作。

这可以解决问题:

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)

这样,每次运行时,它将新数组追加到文件末尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM