从一个循环我得到一个数组。我想将这些数组保存在tempfile
中。
问题是np.savez
只保存循环中的最后一个数组。我想我明白为什么会这样,但不知道怎么做得更好。
为了解决我的问题,我想在mode=a+b
中打开临时文件,目的是从循环中追加新数组。但这不起作用。
到目前为止我的代码:
tmp = TemporaryFile(mode="a+b")
for i in range(10):
array = getarray[i] #demo purpose
np.savez(tmp,array)
tmp.seek(0)
然后使用tempfile读取数组:
tmp_read = np.load(tmp)
print tmp_read.files
[OUTPUT]: ['arr_0']
但我想在tempfile中使用10个数组。任何想法?
感谢
答案 0 :(得分:9)
您可以使用*args
参数将许多数组保存在一个临时文件中。
np.savez(tmp, *getarray[:10])
或:
np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])
答案 1 :(得分:3)
提前抱歉我的英语。
因为函数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
答案 2 :(得分:2)
我不是一个经验丰富的程序员,但这就是我这样做的方式(以防万一它可能在将来帮助某人)。另外,这是我第一次在这里发帖,所以如果我没有遵循某种标准,我会道歉;)
创建npz文件:
import numpy as np
tmp = file("C:\\Windows\\Temp\\temp_npz.npz",'wb')
# some variables
a= [23,4,67,7]
b= ['w','ww','wwww']
c= np.ones((2,6))
# a lit containing the name of your variables
var_list=['a','b','c']
# save the npz file with the variables you selected
str_exec_save = "np.savez(tmp,"
for i in range(len(var_list)):
str_exec_save += "%s = %s," % (var_list[i],var_list[i])
str_exec_save += ")"
exec(str_exec_save)
tmp.close
使用原始名称加载变量:
import numpy as np
import tempfile
tmp = open("C:\\Windows\\Temp\\temp_npz.npz",'rb')
# loading of the saved variables
var_load = np.load(tmp)
# getting the name of the variables
files = var_load.files
# loading then with their original names
for i in range(len(files)):
exec("%s = var_load['%s']" % (files[i],files[i]) )
唯一的区别是变量将变成numpy变量。
答案 3 :(得分:0)
还可以通过使用**
运算符来使用自定义键。
import numpy as np
a1 = [1,2,3]
a2 = [10,20,30]
savez_dict = dict()
for i in ['a1', 'a2']:
savez_dict['key_'+i] = i
np.savez("t.npz", **savez_dict)