简体   繁体   English

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

[英]How to make an equivalent to Fortran's 'access=stream' in python

Let's say i'm making a loop, and after each iteration, y want to extend some array. 假设我正在做一个循环,在每次迭代之后,y要扩展一些数组。

iter 1 ------------> iter 2 --------------> iter 3-------------->.... iter 1 ------------> iter 2 --------------> iter 3 -------------->。 ...

shape=[2,4]---->shape=[2,12]----->shape=[2,36]---->.... 形状= [2,4] ---->形状= [2,12] ----->形状= [2,36] ----> ....

in fortran i used to do this by appending the new numbers to a binary file with: 在fortran中,我曾经通过以下方式将新数字附加到二进制文件中来做到这一点:

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

so this would extend the old array with new values at the end. 因此这将在最后用新值扩展旧数组。

i wish to do the same in python. 我希望在python中做同样的事情。 This is my attempt so far: 到目前为止,这是我的尝试:

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)

But i can't get it to extend the array. 但是我无法扩展数组。 Lets say.. by appeding another [[5.0,5.0],[5.0,5.0]] at the end, 让我们说..在结尾处加上另一个[[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')

to make it [[1.0,2.0,5.0,5.0],[3.0,4.0,5.0,5.0]] after the reading. 阅读后使其为[[1.0,2.0,5.0,5.0],[3.0,4.0,5.0,5.0]]。 How can i do this? 我怎样才能做到这一点?

The other problem i have, is that i would like to be able to make this without knowing the shape of the final array (i know it would be 2 xn ). 我遇到的另一个问题是,我希望能够在不知道最终数组的形状的情况下进行此操作(我知道它将是2 xn)。 But this is not so important. 但这不是那么重要。

edit: the use of 'access=stream' is only to skip having to read format headers and tails. 编辑:“ access = stream”的使用只是跳过必须阅读格式标题和尾部的操作。

This does the trick: 这可以解决问题:

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)

this way, each time its run, it appends the new array to the end of the file. 这样,每次运行时,它将新数组追加到文件末尾。

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

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