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.