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

时间:2016-12-30 19:06:03

标签: python python-3.x attributeerror scandir

当我使用python文档(here)中的示例代码时,会引发AttributeError。示例代码如下:

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()可以正常工作。 有人能告诉我我错过了什么吗?

2 个答案:

答案 0 :(得分:11)

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

{p> This is stated in its documentation您看到的代码段下面)__exit__

  

3.6版中的新功能:添加了对上下文管理器协议scandir方法的支持。 [...]

(强调我的)

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

答案 1 :(得分:4)

文档说

  

3.6版中的新功能:添加了对上下文管理器协议的支持

您可能正在运行较旧的Python版本。