With os.scandir () throws AttributeError: __exit__

An AttributeError occurs when I use the sample code from the python documentation ( here ). The sample 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) 

The result is an 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__ 

Although assigning the os.scandir() variable to a variable works fine. Can someone tell me what I am missing?

+5
source share
2 answers

Support for the context manager was added in Python 3.6 , an attempt to use it with previous versions will result in an error that you see because it is not a context manager (and Python tries to load __exit__ first).

This is indicated in his documentation (right below the code snippet you saw) for scandir :

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

(Emphasis mine)

You can upgrade to Python 3.6 or, if you cannot, not use it as a context manager.

+5
source

Docs say

New in version 3.6: Added support for the context manager protocol

You are probably using an older version of Python.

+2
source

Source: https://habr.com/ru/post/1262097/


All Articles