In [29]: f = open('con.npy')
In [30]: f.__enter__
Out[30]: <function TextIOWrapper.__enter__>
In [31]: f.__exit__
Out[31]: <function TextIOWrapper.__exit__>
In [32]: f.close()
In [33]: arr = np.load('con.npy')
arr 是一个ndarray 并且没有__enter__ 方法。
npz 文件是一个 zip 存档,并且确实有一个 __enter__。它应该可以在with 中使用:
In [34]: ls *.npz
Mcoo.npz Mcsr.npz test.npz
In [35]: d = np.load('test.npz')
In [36]: d.__enter__
Out[36]: <bound method NpzFile.__enter__ of <numpy.lib.npyio.NpzFile object at 0x7fc5e03f7cf8>>
SO 使用 npz 与:
In [39]: with np.load('test.npz') as d:
...: print(list(d.keys()))
...: a = d['a']
...:
['a', 'b']
In [40]: a
Out[40]: array(1)
通常我们不会为npz 使用with,因为像对象一样挂在字典上没有任何成本(据我所知)。
在 TensorFlow 示例中,features = data['features'] 与 data 是一个打开的 NPZ 存档一致。所以尽管npy,这个load 是一个档案。区别是基于文件本身的数据位(_ZIP_PREFIX),而不是文件名。
来自load 文档:
- If the file is a ``.npz`` file, 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']