Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:
with TemporaryDirectory() as tmpdir:
...
Upon exiting the context, the directory and everything contained
in it are removed (unless delete=False is passed or an exception
is raised during cleanup and ignore_cleanup_errors is not True).
Optional Arguments:
suffix - A str suffix for the directory name. (see mkdtemp)
prefix - A str prefix for the directory name. (see mkdtemp)
dir - A directory to create this temp dir in. (see mkdtemp)
ignore_cleanup_errors - False; ignore exceptions during cleanup?
delete - True; whether the directory is automatically deleted.
>>> import tempfile
# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')# read data from file
>>> fp.seek(0)
>>> fp.read()b'Hello world!'# close the file, it will be removed
>>> fp.close()# create a temporary file using a context manager
>>> with tempfile.TemporaryFile()as fp:
... fp.write(b'Hello world!')
... fp.seek(0)
... fp.read()b'Hello world!'
>>>
# file is now closed and removed# create a temporary file using a context manager# close the file, use the name to open the file again
>>> with tempfile.NamedTemporaryFile(delete_on_close=False)as fp:
... fp.write(b'Hello world!')
... fp.close()
... # the file is closed, but not removed
... # open the file again by using its name
... withopen(fp.name, mode='rb')as f:
... f.read()b'Hello world!'
>>>
# file is now removed# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory()as tmpdirname:
... print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed