PyDocs

Nav

File and Directory Access

TemporaryDirectory

tempfile

class · Added in 3.2 (source)
  • TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False, *, delete=True)
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.
Changed in 3.10, 3.12
  • 3.10: Added ignore_cleanup_errors parameter.
  • 3.12: Added the delete parameter.
Members of TemporaryDirectory

c

cleanup
The directory can be explicitly cleaned up by calling the cleanup() method.

n

name
The directory name can be retrieved from the name attribute of the returned object.
1 Example
>>> 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
...     with open(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
from the Python docs
See Also
No see-alsos for tempfile/TemporaryDirectory
0 Notes
No notes for TemporaryDirectory