问题描述
我的目标是:打开一个 binary 文件,将每100个值存储(附加)到该文件中,然后继续进行直到完成.为此,我使用以下简单循环来模拟这一点:
My goal is: Open a binary file, store (append) every 100 values into this file, and continue doing so until finishing. To do so, I use the following simple loop to simulate that:
import numpy as np
import random
alist=[]
c = 1
for i in range(1000):
alist.append(i)
if i == (c*100):
np.array(alist).tofile("file.bin")
print alist
c = c + 1
alist[:] = [] # clear the list before continuing
但是,当我检查file.bin
的大小时,我感到numpy没有追加,而是要替换而不是我想要的.该如何解决?
However, when I check the size of file.bin
, I feel numpy does not append rather it is replacing which is not what I want. How to fix that?
谢谢.
推荐答案
当然,每次(重新)打开要写入的文件时,numpy
都会替换/覆盖旧数据.这几乎是大多数tofile()
类似函数的通用行为(不仅在numpy中).
Of course numpy
is replacing/overwriting your old data every time you (re-)open the file for writing. This is almost universal behavior of most tofile()
like functions (and not only in numpy).
解决方案:在循环之前打开要写入的文件句柄,然后将其传递给tofile()
函数.像这样:
Solution: Open a file handle for writing before the loop and pass that to tofile()
function. Like this:
import numpy as np
import random
alist=[]
c = 1
with open("file.bin", "wb") as f: # or choose 'w+' mode - read "open()" documentation
for i in range(1000):
alist.append(i)
if i == (c*100):
np.array(alist).tofile(f)
print alist
c = c + 1
alist[:] = [] # clear the list before continuing
现在,代码在进入循环之前打开文件,并且tofile()
方法重新使用已经打开的文件句柄,而不是重新打开,从而覆盖了现有文件(在循环运行中创建).
Now the code opens the file before entering the loop and tofile()
method re-uses an already opened file handle instead of re-opening and thus overwriting an existing file (created in the run of the loop).
这篇关于将元素追加到二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!