Python: Why am I receiving an AttributeError: __enter__

12k Views Asked by At

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.

2

There are 2 best solutions below

3
Lie Ryan On BEST ANSWER

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.

0
gopinath rock On

Though I see some of you have answered the problem I would like to add my answer for better clarity.

correct approach:

       with open(fullname, "r") as file:
            content = file.read()

incorrect approach:

       with open(fullname, "r").read() as file:
        

Reason: when you add .read() then its string and not file handler and string is not having built in __enter__ and __exit__ methods and where as file handler has two built-in methods __enter__ and __exit__