Python: Why am I receiving an AttributeError: __enter__
Asked Answered
E

2

5

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.

Etruria answered 4/3, 2019 at 13:13 Comment(5)
"mkdtemp() returns the absolute pathname of the new directory" Need I say more?Easeful
Check out this for an info on context managers. What are going expecting to happen with your code? docs.python.org/2.5/whatsnew/pep-343.htmlBeaudoin
@Beaudoin I wanted to create a temporary directory and I know that tempfile.TemporaryDirectory creates a 'temporary directory', but doesn't show up as an actual directory or folder to input files in before the garbage collector gets too it. I wanted to create an actual directory, assign it a variable name and input files or do whatever operation I want on the directory.Etruria
Not all objects can be used in a with statement. Have you tried test_dir = tempfile.mkdtemp() instead?Octagonal
Then you don't need a with statement. There's no context to manage. The only reason I can think of for wanting a context manager here would be if you wanted the directory to be deleted on exit.Polyphyletic
S
5

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.

Swagsman answered 4/3, 2019 at 13:18 Comment(3)
Using tempfile.TemporaryDirectory() creates a file like 'tmpa665vhxn' that has the type 'file' it is not an actual directory. I would like to make an actual directory I can utilize that is temporary.Etruria
What tells you that tmpa665vhxn is a regular file? It creates a directory for me.Polyphyletic
@Polyphyletic I printed the 'directory' name went to the Temp directory in AppData and looked for the exact name and scrolled over to view the type.Etruria
I
0

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__

Irishman answered 1/6, 2020 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.