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:

import tempfile
tempdir = tempfile.mkdtemp()
print(tempdir) # prints e.g. /tmp/tmpvw0936nd

tempfile.mkdtemp() will automatically create that directory. The directory will not automatically be deleted!

Custom prefix (recommended):

import tempfile
tempdir = tempfile.mkdtemp(prefix="myapplication-")
print(tempdir) # prints e.g. /tmp/myapplication-ztcy6s2w

How to delete the directory

In order to delete the temporary directory including all the files in that directory, use

import shutil
shutil.rmtree(tempdir)