复制 Tensorflow - 使用上下文管理器出现 __enter__ 和 __exit__ 错误

Copying Tensorflow - __enter__ and __exit__ errors using context manager

我尝试使用 with numpy.load('file.npy') 作为栏,但它给我一个错误 attributeError: _enter__ 并且在不同的时间 attributeError: _exit__ .我只是想复制 Tensorflow 页面上显示的示例所做的事情。我不明白为什么他们的代码可以工作,但我的代码——应该是一样的——却不行。

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 是一个存档。区别基于文件本身的数据位 (a _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']