Skip to main content
Log in

Mojo struct

NamedTemporaryFile

A handle to a temporary file.

Fields​

  • ​name (String): Name of the file.

Implemented traits​

AnyType

Methods​

__init__​

__init__(inout self: Self, mode: String = "w", name: Optional[String] = #kgen.none, suffix: String = "", prefix: String = "tmp", dir: Optional[String] = #kgen.none, delete: Bool = 1)

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[String]): 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[String]): Directory in which the file will be created.
  • ​delete (Bool): Whether the file is deleted on close.

__moveinit__​

__moveinit__(inout self: Self, owned existing: Self)

Moves constructor for the file handle.

Args:

  • ​existing (Self): The existing file handle.

__del__​

__del__(owned self: Self)

Closes the file handle.

close​

close(inout self: Self)

Closes the file handle.

read​

read(self: Self, size: SIMD[int64, 1] = -1) -> String

Reads the data from the file.

Args:

  • ​size (SIMD[int64, 1]): Requested number of bytes to read.

Returns:

The contents of the file.

read_bytes​

read_bytes(self: Self, size: SIMD[int64, 1] = -1) -> List[SIMD[uint8, 1], 0]

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

Args:

  • ​size (SIMD[int64, 1]): Requested number of bytes to read.

Returns:

The contents of the file.

seek​

seek(self: Self, offset: SIMD[uint64, 1], whence: SIMD[uint8, 1] = 0) -> SIMD[uint64, 1]

Seeks to the given offset in the file.

Args:

  • ​offset (SIMD[uint64, 1]): The byte offset to seek to from the start of the file.
  • ​whence (SIMD[uint8, 1]): 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:

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(self: Self, data: String)

Write the data to the file.

Args:

  • ​data (String): The data to write to the file.

__enter__​

__enter__(owned self: Self) -> Self

The function to call when entering the context.

Returns:

The file handle.

Was this page helpful?