Skip to main content

Mojo struct

NamedTemporaryFile

struct NamedTemporaryFile

Temporary file with automatic cleanup.

Creates a file that's deleted when closed (by default):

from std.tempfile import NamedTemporaryFile

with NamedTemporaryFile(mode="rw") as f:
    f.write("Hello world!")
    f.seek(0)
    print(f.read())  # "Hello world!"
    print(f.name)    # Access path while open
# File deleted automatically

Set delete=False to keep the file after closing. Use mode="r" for reading, mode="w" for writing, mode="rw" for both.

Fields

  • name (String): Name of the file.

Implemented traits

AnyType, ImplicitlyDestructible, Movable

Methods

__init__

__init__(out self, mode: String = "w", name: Optional[String] = None, suffix: String = "", prefix: String = "tmp", dir: Optional[String] = None, delete: Bool = True)

Create a named temporary file.

This is a wrapper around a FileHandle, os.remove() is called in the close() method if delete is True.

Can be used as a context manager. When used as a context manager, the close() is called when the context manager exits.

Args:

  • mode (String): The mode to open the file in (the mode can be "r" or "w").
  • name (Optional): The name of the temp file. If it is unspecified, then a random name will be provided.
  • suffix (String): Suffix to use for the file name if name is not provided.
  • prefix (String): Prefix to use for the file name if name is not provided.
  • dir (Optional): Directory in which the file will be created.
  • delete (Bool): Whether the file is deleted on close.

Raises:

If the operation fails.

__del__

__del__(deinit self)

Closes the file handle.

close

close(mut self)

Closes the file handle.

Example:

from std.tempfile import NamedTemporaryFile
import std.os

var temp_file = NamedTemporaryFile() # delete=True by default
temp_file.write("Temporary data")
temp_file.close() # File is deleted if delete=True
print(std.os.path.exists(temp_file.name)) # False

temp_file = NamedTemporaryFile(delete=False)
temp_file.write("Temporary data")
temp_file.close() # File is not deleted
print(std.os.path.exists(temp_file.name)) # True
std.os.remove(temp_file.name) # Clean up manually

Raises:

If the operation fails.

read

read(self, size: Int = -1) -> String

Reads the data from the file.

Example:

from std.tempfile import NamedTemporaryFile
from std.pathlib import Path

var p: Path
with NamedTemporaryFile(mode="rw") as f:
    p = f.name.copy()
    f.write("Hello world!")
    _ = f.seek(0)
    print(
        f.read() == "Hello world!"
    )
print(p.exists()) # False

Args:

  • size (Int): Requested number of bytes to read.

Returns:

String: The contents of the file.

Raises:

If the operation fails.

read_bytes

read_bytes(self, size: Int = -1) -> List[UInt8]

Read from file buffer until we have size characters or we hit EOF. If size is negative or omitted, read until EOF.

Example:

from std.tempfile import NamedTemporaryFile
from std.pathlib import Path

var p: Path
var bytes = [Byte(0x48), 0x65, 0x6C, 0x6C, 0x6F] # "Hello"

with NamedTemporaryFile(mode="rw") as f:
    p = f.name.copy()
    f.write_bytes(bytes[:])
    _ = f.seek(0)

    var b = f.read_bytes()
    print(b == bytes) # True

    var s = String(from_utf8_lossy=b)
    print(s) # "Hello"

print(p.exists()) # False

Args:

  • size (Int): Requested number of bytes to read.

Returns:

List: The contents of the file.

Raises:

If the operation fails.

seek

seek(self, offset: UInt64, whence: UInt8 = UInt8(0)) -> UInt64

Seeks to the given offset in the file.

Example:

from std.tempfile import NamedTemporaryFile
from std.pathlib import Path

var p: Path
var bytes = [Byte(0x48), 0x65, 0x6C, 0x6C, 0x6F] # "Hello"

with NamedTemporaryFile(mode="rw") as f:
    p = f.name.copy()
    f.write_bytes(bytes[:])
    _ = f.seek(0)

    var b = f.read_bytes()
    print(b == bytes) # True
    print(String(from_utf8_lossy=b)) # "Hello"

Args:

  • offset (UInt64): The byte offset to seek to from the start of the file.
  • whence (UInt8): The reference point for the offset: os.SEEK_SET = 0: start of file (Default). os.SEEK_CUR = 1: current position. os.SEEK_END = 2: end of file.

Returns:

UInt64: The resulting byte offset from the start of the file.

Raises:

An error if this file handle is invalid, or if file seek returned a failure.

write

write[*Ts: Writable](mut self, *args: *Ts)

Write a sequence of Writable arguments to the provided Writer.

Example:

from std.tempfile import NamedTemporaryFile
from std.pathlib import Path

var p: Path
with NamedTemporaryFile(mode="rw") as f:
    p = f.name
    f.write("Hello world!")
    _ = f.seek(0)
    print(
        f.read() == "Hello world!"
    )

Parameters:

  • *Ts (Writable): Types of the provided argument sequence.

Args:

  • *args (*Ts): Sequence of arguments to write to this Writer.

write_bytes

write_bytes(mut self, bytes: Span[Byte, bytes.origin])

Write a span of bytes to the file.

Example:

from std.tempfile import NamedTemporaryFile

var bytes = [Byte(0x48), 0x65, 0x6C, 0x6C, 0x6F]  # "Hello" in ASCII

with NamedTemporaryFile(mode="rw") as f:
    f.write_bytes(bytes[:])
    _ = f.seek(0)

    var b = f.read_bytes()
    print(b == bytes) # True

    var s = String(from_utf8_lossy=b)
    print(s) # "Hello"

Args:

  • bytes (Span): The byte span to write to this file.

__enter__

__enter__(var self) -> Self

The function to call when entering the context.

Returns:

Self: The file handle.

Was this page helpful?