Mojo struct
TemporaryDirectory
struct TemporaryDirectory
Temporary directory that cleans up automatically.
Creates a directory that's deleted when the context exits:
from tempfile import TemporaryDirectory
import os
def main():
var temp_path: String
with TemporaryDirectory() as tmpdir:
temp_path = tmpdir
print(os.path.exists(tmpdir)) # True
# Use tmpdir for temporary work
print(os.path.exists(temp_path)) # False - cleaned upThe directory and all its contents are removed on exit, even if an error occurs.
Set ignore_cleanup_errors=True to suppress cleanup failures.
Fields
- name (
String): The name of the temporary directory.
Implemented traits
AnyType,
ImplicitlyDestructible
comptime members
__del__is_trivial
comptime __del__is_trivial = False
Methods
__init__
__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): Directory in which the directory will be created. - ignore_cleanup_errors (
Bool): Whether to ignore cleanup errors.
Raises:
If the operation fails.
__enter__
__enter__(self) -> String
The function to call when entering the context.
Returns:
String: The temporary directory name.
__exit__
__exit__(self)
Called when exiting the context with no error.
Raises:
If the operation fails.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!