How to create temporary directory in Python
Note: This example shows how to create a temporary directory that is not automatically deleted. Check out How to create a self-deleting temporary directory in Python for an example on how to create a self-deleting temporary directory!
Minimal example:
tempdir_example.py
import tempfile
tempdir = tempfile.mkdtemp()
print(tempdir) # prints e.g. /tmp/tmpvw0936ndtempfile.mkdtemp() will automatically create that directory. The directory will not automatically be deleted!
Custom prefix (recommended):
example.py
import tempfile
tempdir = tempfile.mkdtemp(prefix="myapplication-")
print(tempdir) # prints e.g. /tmp/myapplication-ztcy6s2wHow to delete the directory
In order to delete the temporary directory including all the files in that directory, use
example.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