【问题标题】:why numpy loadtxt does not work with "with" while load works为什么 numpy loadtxt 在加载工作时不能与“with”一起工作
【发布时间】:2021-09-05 19:41:33
【问题描述】:
np.__version__
Out[307]: '1.20.1'

np.loadtxt 抛出 enter 错误

with np.loadtxt("textfile.txt",delimiter=",") as data1:
     ...:     print ("Hello")
     ...: 

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-300-05181e15f7ec> in <module>
----> 1 with np.loadtxt("textfile.txt",delimiter=",") as data1:
      2     print ("Hello")

AttributeError: __enter__

相同的类,即 np 不会在 load 时抛出 enter 错误。 我想知道 enterexit 是如何绑定到一个类的


with np.load("new.txt.npz") as data:
     ...:     print (data["a"])
     ...: 
     ...: 
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

【问题讨论】:

    标签: python arrays numpy load enter


    【解决方案1】:

    您的示例取自声明的load 文档

    If the file is a .npz file, the returned value supports the context 
    manager protocol in a similar fashion to the open function:
    

    For .npz files, the returned instance of NpzFile class must be closed to 
    avoid leaking file descriptors.
    

    注意returned value 的焦点。在with 上下文中工作的不是numpynp.load,而是调用返回的对象。

    np.load.npy 文件或 np.loadtxt 返回一个 numpy 数组。没有什么需要关闭的。当给定文件名时,这些调用会打开文件进行读取,然后在退出之前将其关闭。

    查看numpy.lib.npyio.py 获取代码。 NpzFile 类有 __enter____exit__ 方法。

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 2010-10-28
      • 2021-04-29
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2021-08-18
      相关资源
      最近更新 更多