问题
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.
回答1:
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.
回答2:
though i see some of you have answered the problem i would like to add my answer for better clarity .
working ------ and correct with open(fullname, "r") as file: content = file.read()
not working ---- and not correct with open(fullname, "r").read() as file:
Reason: when you add .read() then its string and not file handler and string is not havign built in enter and exit methods and where as file handler has two built-in methods enter and exit
来源:https://stackoverflow.com/questions/54984064/python-why-am-i-receiving-an-attributeerror-enter