【问题标题】:Copying Tensorflow - __enter__ and __exit__ errors using context manager [closed]使用上下文管理器复制 Tensorflow - __enter__ 和 __exit__ 错误 [关闭]
【发布时间】:2019-04-27 01:12:29
【问题描述】:

我尝试使用 numpy.load('file.npy') 作为栏,但它给了我一个错误的属性错误:_enter__ 和不同的时间属性错误:_exit__。我只是想复制 Tensorflow 页面上显示的示例。我不明白为什么他们的代码会起作用,但我的——应该是一样的——不会。

【问题讨论】:

  • Tensorflow 示例之所以有效,是因为它实际上是在加载一个 npz 存档(尽管有名称)。

标签: python python-3.x numpy tensorflow tensorflow-datasets


【解决方案1】:
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']

【讨论】:

  • “因为像对象一样挂在字典上没有成本(据我所知)。” - 好吧,除了这个类字典对象保存在文件上,所以now you're leaving the file open too
  • @Eric,我在查看上下文文档之前写了那段内容。
猜你喜欢
  • 2022-10-31
  • 2021-11-04
  • 2017-04-21
  • 1970-01-01
  • 2018-05-22
  • 2017-01-29
  • 1970-01-01
  • 2010-12-31
相关资源
最近更新 更多