如何解决为什么 numpy loadtxt 在加载工作时不适用于“with”
np.__version__
Out[307]: '1.20.1'
np.loadtxt 抛出输入错误
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",") as data1:
2 print ("Hello")
AttributeError: __enter__
相同的类,即 np 不会在 load 时抛出 enter 错误。 我想知道 enter 和 exit 如何绑定到一个类
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]]
解决方法
您的示例取自 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
的关注。在 numpy
上下文中起作用的不是 np.load
或 with
,而是调用返回的对象起作用。
np.load
文件的 .npy
或 np.loadtxt
返回一个 numpy 数组。没有什么需要关闭的。当给定文件名时,这些调用会打开文件进行读取,然后在退出前关闭它。
查看 numpy.lib.npyio.py
以获取代码。类 NpzFile
具有 __enter__
和 __exit__
方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。