Python:为什么我收到AttributeError:__enter__

Jus*_*ick 2 python temporary-directory attributeerror contextmanager

我没有重新分配open关键字,但仍然收到此错误。有任何建议或指导来纠正我的错误吗?

 with tempfile.mkdtemp() as test_dir:
        print(test_dir)
Run Code Online (Sandbox Code Playgroud)

AttributeError: __enter__

我也是python的新手,我很难理解这些概念。

Lie*_*yan 5

您使用的mkdtemp错误。mkdtemp返回路径名称为str,而不是上下文管理器。

如果要使用上下文管理器来管理临时目录,则需要使用TemporaryDirectory,该版本可从Python 3.2及更高版本获得。

  • 什么告诉您“tmpa665vhxn”是一个常规文件?它为我创建了一个目录。 (2认同)