Search code examples
pythonattributeerrorcontextmanagertemporary-directory

Python: Why am I receiving an AttributeError: __enter__


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.


Solution

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