numpy 数组的存储
一个数组的情况
method1: 可取 save—>.npy ----.load()
>>> np.save('./tmp/123.npy',np.array([[1,2,3],[4,5,6]]))
>>> np.load('./tmp/123.npy')
array([[1, 2, 3],
[4, 5, 6]])

method2:savez—>.npz---->load() 是能存取,但是显示不出来
>>> np.savez('./tmp/789.npz',np.array([[1,2,3],[4,5,6]]))
>>> data = np.load('./tmp/789.npz')
>>> data
<numpy.lib.npyio.NpzFile object at 0x000000000B8500C8>
>>> data[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "F:\Anaconda\anaconda\envs\tf2.2.0\lib\site-packages\numpy\lib\npyio.py", line 266, in __getitem__
raise KeyError("%s is not a file in the archive" % key)
KeyError: '0 is not a file in the archive'
>>> print(data)
<numpy.lib.npyio.NpzFile object at 0x000000000B8500C8>
method3 savez(,a=a)---->npz—>load 可取
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.savez('./tmp/111.npz',a = a)
>>> data = np.load('./tmp/111.npz')
>>> data
<numpy.lib.npyio.NpzFile object at 0x000000000B853AC8>
>>> data['a']
array([[1, 2, 3],
[4, 5, 6]])
>>>
多个数组的情况
method1: save—>npy---->load虽然没有报错,但其实只能存取一个数组
>>> import numpy as np
>>> a = np.array([1,2])
>>> b = np.array([3,4])
>>> np.save('./tmp/multi_save',a,b)
>>> np.load('./tmp/multi_save.npy')
array([1, 2])
>>> c = np.load('./tmp/multi_save.npy')
>>> c.size
2
>>> c
array([1, 2])
>>>
method2: savez ----npz-----load
>>> import numpy as np
>>> a = np.array([1,2])
>>> b = np.array([3,4])
>>> np.savez('./tmp/multi_savez',train=a, test=b)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression
>>> np.savez('./tmp/multi_savez', train = a , test = b)
>>> data = np.load('./tmp/multi_savez.npz')
>>> data['train']
array([1, 2])
>>> data['test']
array([3, 4])
>>> data.close()
>>> import numpy as np
>>> a = np.array([1,2])
>>> b = np.array([3,4])
>>> np.savez('./tmp/multi_savez.npz',train = a, test = b)
>>> with np.load('./tmp/multi_savez.npz') as data:
... a = data['train']
... b = data['test']
...
>>> a
array([1, 2])
>>> b
array([3, 4])
>>>
从中可以分析到的东西
-
如何对个数组 起一个关键字
-
‘./tmp/multi_savez’ 起的文件名并没有在后面写.npz,但是也自动生成.npz文件,
也可以带.npz来命名 -
查询时使用data[关键字]
-
data.close()

后面再输入data.close()就可以删掉了multi_savez.npz
5.If the file is a.npzfile, the returned value supports the
context manager protocol in a similar fashion to the open function::with load('foo.npz') as data: a = data['a']The underlying file descriptor is closed when exiting the ‘with’
block.
如果是用with np.load() as data: 的话, 后面不用data.close()就可以删除multi_savez.npy
6.如果文件夹中本身就存在multi_savez.npz 文件,并不影响再次写入

这篇博客探讨了numpy中一个数组和多个数组的存储与读取方法,包括save、savez以及load的使用。在单个数组情况下,save与savez都能实现存储,但savez在加载时无法直接显示内容;而在多个数组场景下,save方法只能保存一个数组,savez则可保存多个并允许通过关键字访问。利用with语句加载文件时,数据关闭后文件会被自动删除。
1077

被折叠的 条评论
为什么被折叠?



