Python: Why am I receiving an AttributeError: __enter__

独自空忆成欢 提交于 2021-02-10 05:14:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!