How to create a temporary directory and get its path/ file name? How to create a temporary directory and get its path/ file name? python python

How to create a temporary directory and get its path/ file name?


Use the mkdtemp() function from the tempfile module:

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


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

This is straight from the examples:

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

If you would like to keep the directory a bit longer, you could do something like this:

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

The documentation also says that "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." So at the end of the program, for example, Python will clean up the directory if it wasn't explicitly removed. Python's unittest may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory... if you rely on this, though.


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:        yield    finally:        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