對不起,我的英語進步。
因爲函數savez打開文件,寫入所有變量,然後關閉文件,數據在被調用時被覆蓋。
savez很簡單。你可以找到代碼https://github.com/numpy/numpy/blob/master/numpy/lib/npyio.py
如何實現「your_own_savez」,然後使用下面的代碼。
tmp = TemporaryFile()
f = my_savez(tmp)
for i in range(10):
array = getarray[i] #demo purpose
f.savez(array)
f.close()
tmp.seek(0)
tmp_read = np.load(tmp)
print tmp_read.files
這是我的快速和骯髒的代碼。
import numpy as np
import tempfile
class my_savez(object):
def __init__(self, file):
# Import is postponed to here since zipfile depends on gzip, an optional
# component of the so-called standard library.
import zipfile
# Import deferred for startup time improvement
import tempfile
import os
if isinstance(file, basestring):
if not file.endswith('.npz'):
file = file + '.npz'
compression = zipfile.ZIP_STORED
zip = self.zipfile_factory(file, mode="w", compression=compression)
# Stage arrays in a temporary file on disk, before writing to zip.
fd, tmpfile = tempfile.mkstemp(suffix='-numpy.npy')
os.close(fd)
self.tmpfile = tmpfile
self.zip = zip
self.i = 0
def zipfile_factory(self, *args, **kwargs):
import zipfile
import sys
if sys.version_info >= (2, 5):
kwargs['allowZip64'] = True
return zipfile.ZipFile(*args, **kwargs)
def savez(self, *args, **kwds):
import os
import numpy.lib.format as format
namedict = kwds
for val in args:
key = 'arr_%d' % self.i
if key in namedict.keys():
raise ValueError("Cannot use un-named variables and keyword %s" % key)
namedict[key] = val
self.i += 1
try:
for key, val in namedict.iteritems():
fname = key + '.npy'
fid = open(self.tmpfile, 'wb')
try:
format.write_array(fid, np.asanyarray(val))
fid.close()
fid = None
self.zip.write(self.tmpfile, arcname=fname)
finally:
if fid:
fid.close()
finally:
os.remove(self.tmpfile)
def close(self):
self.zip.close()
tmp = tempfile.TemporaryFile()
f = my_savez(tmp)
for i in range(10):
array = np.zeros(10)
f.savez(array)
f.close()
tmp.seek(0)
tmp_read = np.load(tmp)
print tmp_read.files
for k, v in tmp_read.iteritems():
print k, v
如果數組太大而無法在內存中完全分配,並且您想堅持使用for循環,請對每個數組使用一個文件。我不認爲你可以在追加模式下使用'.npz'文件。 – gg349
'.npz'是一個標準的zip壓縮文件。這意味着'.npy'文件可以通過任何歸檔工具添加或刪除(從Python或shell或窗口中)。玩起來很容易。 – hpaulj