与os.scandir()一起引发AttributeError:__exit__ [英] with os.scandir() raises AttributeError: __exit__

查看:170
本文介绍了与os.scandir()一起引发AttributeError:__exit__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用python文档中的示例代码(

An AttributeError is raised when I use the example code from python's documentation (here). The example code is as follows:

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()分配给变量也可以. 有人可以告诉我我想念什么吗?

Although, assigning os.scandir() to a variable works fine. Could someone tell me what I'm missing?

推荐答案

Python 3.6 中添加了上下文管理器支持,尝试在以前的版本中使用它会引起您看到的错误,因为它不是不是上下文管理器(Python会先尝试加载__exit__).

The context manager support was added in Python 3.6, trying to use it with previous versions will raise the error you see since it isn't a context manager (and Python tries to load __exit__ first).

在其文档中进行了说明(就在您看到的代码段的正下方):scandir:

This is stated in its documentation (right under the code snippet you saw) for scandir:

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

New in version 3.6: Added support for the context manager protocol and the close() method. [...]

(强调我的)

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

You can either update to Python 3.6 or, if you can't, don't use it as a context manager.

这篇关于与os.scandir()一起引发AttributeError:__exit__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆