For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
TemporaryDirectory
struct TemporaryDirectory
Temporary directory that cleans up automatically.
For example, this creates a directory that's deleted when the context ends:
from std.tempfile import TemporaryDirectory
import std.os
def main() raises:
var temp_path: String
with TemporaryDirectory() as tmpdir:
temp_path = tmpdir
print(std.os.path.exists(tmpdir)) # True
# Use tmpdir for temporary work
print(std.os.path.exists(temp_path)) # False - cleaned up
The directory and all its contents are removed on exit, even if an error
occurs inside the context. Such an error is discarded as long as cleanup
succeeds. Set ignore_cleanup_errors=True to suppress cleanup failures;
errors raised inside the context are then discarded even when the directory
can't be fully removed. Use try inside the context when you need to
handle or report an error.
The directory name is built as prefix followed by 8 random characters and
suffix. The random characters come from std.random, so every run of the
program generates the same sequence of names, skipping any names already in
use. Call seed() from std.random first when you need different names
across runs.
Fields
- name (
String): The name of the temporary directory.
Implemented traits
Methods
__init__
def __init__(out self, suffix: String = "", prefix: String = "tmp", dir: Optional[String] = None, ignore_cleanup_errors: Bool = False)
Create a temporary directory.
Can be used as a context manager. When used as a context manager, the directory is removed when the context manager exits.
Args:
- suffix (
String): Suffix to use for the directory name. - prefix (
String): Prefix to use for the directory name. - dir (
Optional[String]): Directory in which the directory will be created. - ignore_cleanup_errors (
Bool): Whether to ignore cleanup errors.
Raises:
If the operation fails.
__enter__
def __enter__(self) -> String
The function to call when entering the context.
Returns:
String: The temporary directory name.
__exit__
def __exit__(self)
Called when exiting the context with no error.
Raises:
If the operation fails.