使用os.scandir()引发AttributeError:__ exit__

and*_*rge 11 python attributeerror scandir python-3.x

AttributeError当我使用python文档中的示例代码(这里)时引发了一个问题.示例代码如下:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
Run Code Online (Sandbox Code Playgroud)

结果是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__
Run Code Online (Sandbox Code Playgroud)

虽然,分配os.scandir()给变量工作正常.有人能告诉我我错过了什么吗?

Jim*_*ard 12

Python 3.6中添加了上下文管理器支持,尝试将其与先前版本一起使用将引发您看到的错误,因为它不是上下文管理器(并且Python尝试首先加载__exit__).

这在其文档中(您看到的代码段下面)中说明scandir:

版本3.6中的新增功能:添加了对上下文管理器协议close()方法的支持.[...]

(强调我的)

您可以更新到Python 3.6,如果不能,也可以不将其用作上下文管理器.