In Python 3, TemporaryDirectory from the tempfile module can be used.

From the examples:

import tempfile

with tempfile.TemporaryDirectory() as tmpdirname:
     print('created temporary directory', tmpdirname)

# directory and contents have been removed

To manually control when the directory is removed, don't use a context manager, as in the following example:

import tempfile

temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()

The documentation also says:

On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.

At the end of the program, for example, Python will clean up the directory if it wasn't removed, e.g. by the context manager or the cleanup() method. Python's unittest may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory... if you rely on this, though.

Answer from Nagev on Stack Overflow
🌐
ProgramCreek
programcreek.com › python › example › 111 › tempfile.mkdtemp
Python Examples of tempfile.mkdtemp
def downloadDemo(which): try: downloadDir = tempfile.mkdtemp() archivePath = "{}/svviz-data.zip".format(downloadDir) # logging.info("Downloading...") downloadWithProgress("http://svviz.github.io/svviz/assets/examples/{}.zip".format(which), archivePath) logging.info("Decompressing...") archive = zipfile.ZipFile(archivePath) archive.extractall("{}".format(downloadDir)) if not os.path.exists("svviz-examples"): os.makedirs("svviz-examples/") shutil.move("{temp}/{which}".format(temp=downloadDir, which=which), "svviz-examples/") except Exception as e: print("error downloading and decompressing example data: {}".format(e)) return False if not os.path.exists("svviz-examples"): print("error finding example data after download and decompression") return False return True
🌐
Python
docs.python.org › 3 › library › tempfile.html
tempfile — Generate temporary files and directories
Beware that if you set tempdir to a bytes value, there is a nasty side effect: The global default return type of mkstemp() and mkdtemp() changes to bytes when no explicit prefix, suffix, or dir arguments of type str are supplied. Please do not write code expecting or depending on this.
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › tempfile.mkdtemp.html
tempfile.mkdtemp() — Python Standard Library
tempfile.mkdtemp() View page source · tempfile.mkdtemp(suffix='', prefix='tmp', dir=None)[source]¶ · User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. Arguments are as for mkstemp, except that the ‘text’ argument ...
🌐
Python Module of the Week
pymotw.com › 2 › tempfile
tempfile – Create temporary filesystem resources. - Python Module of the Week
import os import tempfile directory_name = tempfile.mkdtemp() print directory_name # Clean up the directory yourself os.removedirs(directory_name) Since the directory is not “opened” per se, you have to remove it yourself when you are done with it. $ python tempfile_mkdtemp.py /var/folders/5q/8gk0wq888xlggz008k8dr7180000hg/T/tmpE4plSY
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-temporary-files-and-directories-using-python-tempfile
Create temporary files and directories using tempfile - GeeksforGeeks
July 15, 2025 - import tempfile secure_temp_dir = tempfile.mkdtemp(prefix="pre_",suffix="_suf") print(secure_temp_dir) ... We can set the location where the files are stored by setting the tempdir attribute.
🌐
W3Schools
w3schools.com › python › ref_module_tempfile.asp
Python tempfile Module
HTML Certificate CSS Certificate JavaScript Certificate Front End Certificate SQL Certificate Python Certificate PHP Certificate jQuery Certificate Java Certificate C++ Certificate C# Certificate XML Certificate ... W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.
Find elsewhere
🌐
Readthedocs
anyio.readthedocs.io › en › stable › tempfile.html
Asynchronous Temporary File and Directory — AnyIO 4.14.2 documentation
from anyio import mkstemp, mkdtemp, gettempdir, run import os async def main(): fd, path = await mkstemp(suffix=".txt", prefix="mkstemp_", text=True) print(f"Created temp file: {path}") temp_dir = await mkdtemp(prefix="mkdtemp_") print(f"Created temp dir: {temp_dir}") print(f"Default temp dir: {await gettempdir()}") os.remove(path) run(main) Note · Using these functions requires manual cleanup of the created files and directories. See also · Python Standard Library: tempfile (official documentation)
🌐
TechOverflow
techoverflow.net › 2019 › 07 › 15 › how-to-create-temporary-directory-in-python
How to create temporary directory in Python | TechOverflow
July 14, 2019 - import tempfile tempdir = tempfile.mkdtemp(prefix="myapplication-") print(tempdir) # prints e.g. /tmp/myapplication-ztcy6s2w · In order to delete the temporary directory including all the files in that directory, use · example.py · Copy Download · import shutil shutil.rmtree(tempdir) Check out similar posts by category: Python ·
🌐
GitHub
github.com › python › cpython › blob › main › Lib › tempfile.py
cpython/Lib/tempfile.py at main · python/cpython
>>> tempfile.mkdtemp(suffix=b'') b'/tmp/tmppbi8f0hy' · This module also provides some data items to the user: · TMP_MAX - maximum number of names that will be tried before · giving up. tempdir - If this is set to a string before the first use of ·
Author   python
🌐
Safjan
safjan.com › home › note › mastering temporary files and directories with...
Mastering Temporary Files and Directories with Python's tempfile Module
July 12, 2023 - import tempfile temp_file, temp_file_path = tempfile.mkstemp() print(f'Temporary file path: {temp_file_path}') temp_dir_path = tempfile.mkdtemp() print(f'Temporary directory path: {temp_dir_path}') In this article, we've explored the powerful features of Python's tempfile module, covering common use-cases and some lesser-known features.
🌐
Appdividend
appdividend.com › creating-temporary-files-and-directories-efficiently-in-python
How to Create Temporary Files and Directories in Python
September 7, 2025 - from tempfile import mkdtemp import os # Create a temporary directory using mkdtemp() dir_path = mkdtemp() try: print(f"Directory: {dir_path}") finally: os.rmdir(dir_path) # Output: Directory: /var/folders/8m/x21znv0n7r5383bnmngj4kmw0000kb/T/tmpx0c8i6bc · That’s all! ... With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge. How to Create Directory If It Does Not Exist in Python
🌐
Real Python
realpython.com › ref › stdlib › tempfile
tempfile | Python Standard Library – Real Python
In this tutorial, you'll be examining a couple of methods to get a list of files and folders in a directory with Python. You'll also use both methods to recursively list directory contents.
🌐
Read the Docs
python.readthedocs.io › en › latest › library › tempfile.html
11.6. tempfile — Generate temporary files and directories
Beware that if you set tempdir to a bytes value, there is a nasty side effect: The global default return type of mkstemp() and mkdtemp() changes to bytes when no explicit prefix, suffix, or dir arguments of type str are supplied. Please do not write code expecting or depending on this.
🌐
Openstack
security.openstack.org › guidelines › dg_using-temporary-files-securely.html
Create, use, and remove temporary files securely — OpenStack Security Advisories 0.0.1.dev342 documentation
May 7, 2015 - import os import tempfile tmpdir = tempfile.mkdtemp() predictable_filename = 'myfile' # Ensure the file is read/write by the creator only saved_umask = os.umask(0077) path = os.path.join(tmpdir, predictable_filename) print path try: with open(path, "w") as tmp: tmp.write("secrets!") except IOError as e: print 'IOError' else: os.remove(path) finally: os.umask(saved_umask) os.rmdir(tmpdir)