How can I create a temporary directory and get its path in Python?

6

Best Answer


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

From the examples:

import tempfilewith 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 tempfiletemp_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.

Use the mkdtemp() function from the tempfile module:

import tempfileimport shutildirpath = tempfile.mkdtemp()# ... do stuff with dirpathshutil.rmtree(dirpath)

To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:

import contextlibimport osimport shutilimport tempfile@contextlib.contextmanagerdef cd(newdir, cleanup=lambda: True):prevdir = os.getcwd()os.chdir(os.path.expanduser(newdir))try:yieldfinally:os.chdir(prevdir)cleanup()@contextlib.contextmanagerdef tempdir():dirpath = tempfile.mkdtemp()def cleanup():shutil.rmtree(dirpath)with cd(dirpath, cleanup):yield dirpathdef main():with tempdir() as dirpath:pass # do something here

The docs suggest using the TemporaryDirectory context manager, which creates a temporary directory, and automatically removes it when exiting the context manager:

import tempfilewith tempfile.TemporaryDirectory() as tmpdirname:print('created temporary directory', tmpdirname)# Outside the context manager, directory and contents have been removed.

Using pathlib to facilitate path manipulation on top of tempfile makes it possible to create new paths with the / path operator of pathlib:

import tempfilefrom pathlib import Pathwith tempfile.TemporaryDirectory() as tmpdirname:temp_dir = Path(tmpdirname)file_name = temp_dir / "test.txt"file_name.write_text("bla bla bla")print(temp_dir, temp_dir.exists())# /tmp/tmp81iox6s2 Trueprint(file_name, "contains", file_name.open().read())# /tmp/tmp81iox6s2/test.txt contains bla bla bla

Outside the context manager, files have been destroyed

print(temp_dir, temp_dir.exists())# /tmp/tmp81iox6s2 Falseprint(file_name, file_name.exists())# /tmp/tmp81iox6s2/test.txt False

In python 3.2 and later, there is a useful contextmanager for this in the stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory

If I get your question correctly, you want to also know the names of the files generated inside the temporary directory?If so, try this:

import osimport tempfilewith tempfile.TemporaryDirectory() as tmp_dir:# generate some random files in itfiles_in_dir = os.listdir(tmp_dir)