如何在 Python 中创建临时目录
注意:此示例展示如何创建不会自动删除的临时目录。请查看如何在 Python 中创建自删除临时目录了解如何创建自删除临时目录的示例!
最小示例:
tempdir_example.py
import tempfile
tempdir = tempfile.mkdtemp()
print(tempdir) # 打印例如 /tmp/tmpvw0936ndtempfile.mkdtemp() 将自动创建该目录。该目录不会自动删除!
自定义前缀(推荐):
tempdir_custom_prefix.py
import tempfile
tempdir = tempfile.mkdtemp(prefix="myapplication-")
print(tempdir) # 打印例如 /tmp/myapplication-ztcy6s2w如何删除目录
为了删除临时目录及该目录中的所有文件,使用
tempdir_delete.py
import shutil
shutil.rmtree(tempdir)Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow