Python: Why am I receiving an AttributeError: __enter__

Justin Reddick picture Justin Reddick · Mar 4, 2019 · Viewed 7.3k times · Source

I am not reassigning the open keyword yet still receive this error. Any suggestions or direction to fix my error?

 with tempfile.mkdtemp() as test_dir:
        print(test_dir)

AttributeError: __enter__

I am also new to python and I am having a hard time understanding these concepts.

Answer

Lie Ryan picture Lie Ryan · Mar 4, 2019

You're using mkdtemp incorrectly. mkdtemp returns the path name as str, not a context manager.

If you want a context manager for managing a temporary directory, you need to use TemporaryDirectory, which is available from Python 3.2 and above.