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
🌐
Python
docs.python.org › 3 › library › tempfile.html
tempfile — Generate temporary files and directories
Changed in version 3.12: mkdtemp() now always returns an absolute path, even if dir is relative. ... Return the name of the directory used for temporary files. This defines the default value for the dir argument to all functions in this module.
🌐
Python Module of the Week
pymotw.com › 2 › tempfile
tempfile – Create temporary filesystem resources. - Python Module of the Week
The tempfile module provides several functions for creating filesystem resources securely. TemporaryFile() opens and returns an un-named file, NamedTemporaryFile() opens and returns a named file, and mkdtemp() creates a temporary directory and returns its name.
🌐
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
🌐
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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › create-temporary-files-and-directories-using-python-tempfile
Create temporary files and directories using tempfile - GeeksforGeeks
January 18, 2024 - Python3 · import tempfile secure_temp = tempfile.mkstemp(prefix="pre_",suffix="_suf") print(secure_temp) Output: (71, '/tmp/pre_i5us4u9j_suf') Similarly, we can create a secure temporary directory using mkdtemp() method. Python3 · import tempfile secure_temp_dir = tempfile.mkdtemp(prefix="pre_",suffix="_suf") print(secure_temp_dir) Output: /tmp/pre_9xmtwh4u_suf ·
Find elsewhere
🌐
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.
🌐
Reddit
reddit.com › r/learnpython › tempfile.mkdtemp in memory?
r/learnpython on Reddit: tempfile.mkdtemp in memory?
November 19, 2013 -

Hi, I'm calling some external software from within python, which basically uses a system call such as os.system("external program -input_file x -output_file y"). For this, I'm using a temporarily created directory (tempfile.mkdtemp) and it works perfectly.

However, I'd like to speed things up and write as little as possible to my hard disk. Therefore I'd like to write into memory, however, I want to maintain a directory and file names that I can use with the os.system call. tempfile.SpooledTemporaryFile does not work for this as far as I can see. Has anybody tried something similar or can help?

Thanks!

🌐
Real Python
realpython.com › ref › stdlib › tempfile
tempfile | Python Standard Library – Real Python
The Python tempfile module provides a simple way to create temporary files and directories.
🌐
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)
🌐
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
Top answer
1 of 5
98

To manage resources (like files) in Python, best practice is to use the with keyword, which automatically releases the resources (i.e., cleans up, like closing files); this is available from Python 2.5.

From Python 3.2, you can use tempfile.TemporaryDirectory() instead of tempfile.mkdtmp() – this is usable in with and automatically cleans up the directory:

from tempfile import TemporaryDirectory

with TemporaryDirectory() as temp_dir:
    # ... do something with temp_dir
# automatically cleaned up when context exited

If you are using an earlier version of Python (at least 2.5, so have with), you can use backports.tempfile; see Nicholas Bishop’s answer to tempfile.TemporaryDirectory context manager in Python 2.7.

It’s easy and instructive to roll your own class, called a context manager. The return value of the __enter__() method is bound to the target of the as clause, while the __exit__() method is called when the context is exited – even by exception – and performs cleanup.

import shutil
import tempfile

class TemporaryDirectory(object):
    """Context manager for tempfile.mkdtemp() so it's usable with "with" statement."""
    def __enter__(self):
        self.name = tempfile.mkdtemp()
        return self.name

    def __exit__(self, exc_type, exc_value, traceback):
        shutil.rmtree(self.name)

You can simplify this with the @contextlib.contextmanager decorator, so you don’t need to write a context manager manually. The code prior to the yield is executed when entering the context, the yielded value is bound to the target of the as, and the code after the yield is executed when exiting the context. This is fundamentally a coroutine that encapsulates the resource acquisition and release, with the yield yielding control to the suite (body) of the with clause. Note that here you do need to have a try...finally block, as @contextlib.contextmanager does not catch exceptions in the yield – this just factors the resource management into a coroutine.

from contextlib import contextmanager
import tempfile
import shutil

@contextmanager
def TemporaryDirectory():
    name = tempfile.mkdtemp()
    try:
        yield name
    finally:
        shutil.rmtree(name)

As simplylizz notes, if you don’t mind the directory already being deleted (which the above code assumes does not happen), you can catch the “No such file or directory” exception as follows:

import errno
# ...
try:
    shutil.rmtree(self.name)
except OSError as e:
    # Reraise unless ENOENT: No such file or directory
    # (ok if directory has already been deleted)
    if e.errno != errno.ENOENT:
        raise

You can compare with the standard implementation in tempfile.py; even this simple class has had bugs and evolved over the years.

For background on with, see:

  • The Python Tutorial: Methods of File Objects
  • With Statement Context Managers
  • PEP 343 -- The "with" Statement
2 of 5
36

Read the documentation, it's simple. ;) From the docs: the directory is readable, writable, and searchable only by the creating user ID.

To delete temp directory try something like this:

import errno
import shutil
import tempfile

try:
    tmp_dir = tempfile.mkdtemp()  # create dir
    # ... do something
finally:
    try:
        shutil.rmtree(tmp_dir)  # delete directory
    except OSError as exc:
        if exc.errno != errno.ENOENT:  # ENOENT - no such file or directory
            raise  # re-raise exception

Also you can try tempdir package or see its sources.

🌐
Geek Python
geekpython.in › tempfile-in-python
How To Use tempfile To Create Temporary Files and Directories in Python
August 15, 2023 - mkstemp is used for creating a temporary file in the most secure manner possible and mkdtemp is used to create a temporary directory in the most secure manner possible.
🌐
W3Schools
w3schools.com › python › ref_module_tempfile.asp
Python tempfile Module
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.