An AttributeError
当我使用 python 文档中的示例代码时引发(here https://docs.python.org/3/library/os.html#os.scandir)。示例代码如下:
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_file():
print(entry.name)
结果是AttributeError
:
D:\Programming>test.py
Traceback (most recent call last):
File "D:\Programming\test.py", line 3, in <module>
with os.scandir() as it:
AttributeError: __exit__
虽然,分配os.scandir()
到一个变量工作正常。
有人可以告诉我我错过了什么吗?
添加了上下文管理器支持Python 3.6,尝试将它与以前的版本一起使用会引发您看到的错误,因为它不是上下文管理器(并且Python尝试加载__exit__
first).
这是在其文档中说明的 https://docs.python.org/3/library/os.html#os.scandir (就在下面您看到的代码片段)scandir
:
3.6 版新增内容:添加了对上下文管理器协议的支持和close()
方法。 [...]
(Emphasis mine)
您可以更新到 Python 3.6,如果不能,请不要将其用作上下文管理器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)