如何将大量ndarray写入一个文件,其中每个ndarray都保存在一行中



我有很多ndarray对象要保存。我想一个接一个地保存这些ndarray,这意味着每个ndarray都保存在文件中的一行中。我发现np.savez似乎对这种情况没有用处。我该怎么做?谢谢

我试过这样的方法:

保存这些ndarrays时,

with open(file, 'a') as f:
for i in range(n)
f.write(str(ndarry[i].tostring()) + 'n')

当加载并恢复它们时,

list_array = []
with open(file, 'a') as f:
line = f.reanline().strip('n')
while line
ndarray = np.fromstring(line, dtype=np.int64).reshape((2,3))
list_array.append(ndarray)
line = f.reanline().strip('n')

但我得到了"ValueError:字符串大小必须是元素大小的倍数">

您是否尝试仅为一个数组调试行写入/读取?详细看一下步骤?

In [568]: arr = np.arange(3)                                                                           
In [569]: arr                                                                                          
Out[569]: array([0, 1, 2])
In [570]: arr.tostring()                                                                               
Out[570]: b'x00x00x00x00x00x00x00x00x01x00x00x00x00x00x00x00x02x00x00x00x00x00x00x00'

b告诉我们这是一个字节字符串(就像旧的py2字符串一样(。然后用py3字符串"包装"它:

In [571]: str(arr.tostring())+'n'                                                                     
Out[571]: "b'\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00'n"

现在尝试阅读:

In [572]: _.strip('n')                                                                                
Out[572]: "b'\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00'"
In [573]: np.fromstring(_, np.int64)                                                                   
/usr/local/bin/ipython3:1: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
#!/usr/bin/python3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-573-fa8feb7879b7> in <module>
----> 1 np.fromstring(_, np.int64)
ValueError: string size must be a multiple of element size

我可以从tostring输出恢复原始阵列:

In [574]: np.frombuffer(arr.tostring(), np.int64)                                                      
Out[574]: array([0, 1, 2])

向文件中写入二进制字符串的所有str和换行符都会扰乱读取。

最新更新