import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
要手动控制何时删除目录,不要使用上下文管理器,如下例所示:
import tempfile
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()
文档还说:
在完成上下文或销毁临时目录对象时,新创建的临时目录及其所有内容将从文件系统中删除。
例如,在程序结束时,如果目录没有被上下文管理器或cleanup()方法删除,Python将清理该目录。不过,如果你依赖于此,Python的unittest可能会抱怨ResourceWarning: Implicitly cleaning up <TemporaryDirectory...。
import tempfile
# create a temporary directory using the context manager
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# Outside the context manager, directory and contents have been removed.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmpdirname:
temp_dir = Path(tmpdirname)
print(temp_dir, temp_dir.exists())
file_name = temp_dir / "test.txt"
file_name.write_text("bla bla bla")
print(file_name, "contains", file_name.open().read())
# /tmp/tmp81iox6s2 True
# /tmp/tmp81iox6s2/test.txt contains bla bla bla