Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

with os.scandir() raises AttributeError: __exit__

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)

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 os.scandir() to a variable works fine. Could someone tell me what I'm missing?

like image 879
andrew_berge Avatar asked Dec 30 '16 19:12

andrew_berge


People also ask

What does OS Scandir return?

Like the other functions in the os module, scandir() accepts either a bytes or str object for the path parameter, and returns the DirEntry.name and DirEntry.

Is Scandir faster than Listdir?

Project description. scandir() is a directory iteration function like os. listdir(), except that instead of returning a list of bare filenames, it yields DirEntry objects that include file type and stat information along with the name. Using scandir() increases the speed of os.


2 Answers

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).

This is stated in its documentation (right under 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 either update to Python 3.6 or, if you can't, don't use it as a context manager.

like image 132
Dimitris Fasarakis Hilliard Avatar answered Oct 12 '22 17:10

Dimitris Fasarakis Hilliard


The docs say

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

You are probably running an older Python version.

like image 45
Nils Werner Avatar answered Oct 12 '22 16:10

Nils Werner