Skip to main content

Mojo struct

Path

struct Path

The Path object.

Fields

  • path (String): The underlying path string representation.

Implemented traits

AnyType, Boolable, Copyable, Equatable, Hashable, ImplicitlyCopyable, ImplicitlyDestructible, Movable, PathLike, Stringable, Writable

comptime members

__copyinit__is_trivial

comptime __copyinit__is_trivial = False

__del__is_trivial

comptime __del__is_trivial = False

__moveinit__is_trivial

comptime __moveinit__is_trivial = False

Methods

__init__

__init__(out self)

Initializes a path with the current directory.

Raises:

If the operation fails.

__init__(out self, path: StringSlice[origin])

Initializes a path with the provided path.

Args:

@implicit __init__(out self, var path: String)

Initializes a path with the provided path.

Args:

  • path (String): The file system path.

@implicit __init__(out self, path: StringLiteral[value])

Initializes a path with the provided path.

Args:

__bool__

__bool__(self) -> Bool

Checks if the path is not empty.

Returns:

Bool: True if the path length is greater than zero, and False otherwise.

__eq__

__eq__(self, other: Self) -> Bool

Returns True if the two paths are equal.

Args:

  • other (Self): The other path to compare against.

Returns:

Bool: True if the paths are equal and False otherwise.

__eq__(self, other: StringSlice[origin]) -> Bool

Returns True if the two paths are equal.

Args:

  • other (StringSlice): The other path to compare against.

Returns:

Bool: True if the String and Path are equal, and False otherwise.

__truediv__

__truediv__(self, suffix: Self) -> Self

Joins two paths using the system-defined path separator.

Args:

  • suffix (Self): The suffix to append to the path.

Returns:

Self: A new path with the suffix appended to the current path.

__truediv__(self, suffix: StringSlice[origin]) -> Self

Joins two paths using the system-defined path separator.

Args:

  • suffix (StringSlice): The suffix to append to the path.

Returns:

Self: A new path with the suffix appended to the current path.

__itruediv__

__itruediv__(mut self, suffix: StringSlice[origin])

Joins two paths using the system-defined path separator.

Args:

  • suffix (StringSlice): The suffix to append to the path.

__str__

__str__(self) -> String

Returns a string representation of the path.

Returns:

String: A string representation of the path.

write_to

write_to(self, mut writer: T)

Formats this path to the provided Writer.

Args:

  • writer (T): The object to write to.

__fspath__

__fspath__(self) -> String

Returns a string representation of the path.

Returns:

String: A string representation of the path.

__repr__

__repr__(self) -> String

Returns a printable representation of the path.

Returns:

String: A printable representation of the path.

stat

stat(self) -> stat_result

Returns the stat information on the path.

Examples:

from pathlib import Path

try:
    p = Path()       # Path to cwd
    print(p.stat())  # os.stat_result(...)
except e:
    print(e)

Returns:

stat_result: A stat_result object containing information about the path.

Raises:

If the operation fails.

lstat

lstat(self) -> stat_result

Returns the lstat information on the path. This is similar to stat, but if the file is a symlink then it gives you information about the symlink rather than the target.

Returns:

stat_result: A stat_result object containing information about the path.

Raises:

If the operation fails.

exists

exists(self) -> Bool

Returns True if the path exists and False otherwise.

Examples:

from pathlib import Path

var p = Path("./path-to-nowhere")
print("Exists" if p.exists() else "Does not exist") # Does not exist

Returns:

Bool: True if the path exists on disk and False otherwise.

expanduser

expanduser(self) -> Self

Expands a prefixed ~ with $HOME on posix If environment variables are not set or the path is not prefixed with ~, returns the path unmodified.

Examples:

from pathlib import Path

try:
    var p = Path("~")
    assert_true(p.expanduser() == Path.home())
except e:
    print(e)

Returns:

Self: The expanded path.

Raises:

If the operation fails.

home

static home() -> Self

Returns $HOME on posix. If environment variables are not set it returns ~.

Examples:

from pathlib import Path

try:
    var p = Path("~")
    assert_true(p.expanduser() == Path.home())
except e:
    print(e)

Returns:

Self: Path to user home directory.

Raises:

If the operation fails.

is_dir

is_dir(self) -> Bool

Returns True if the path is a directory and False otherwise.

Examples:

from pathlib import Path

try:
    assert_true(Path.home().is_dir())
except e:
    print(e)

Returns:

Bool: Return True if the path points to a directory (or a link pointing to a directory).

is_file

is_file(self) -> Bool

Returns True if the path is a file and False otherwise.

Examples:

from pathlib import Path

try:
    assert_false(Path.home().is_file())
except e:
    print(e)

Returns:

Bool: Return True if the path points to a file (or a link pointing to a file).

read_text

read_text(self) -> String

Returns content of the file.

Examples:

from pathlib import Path

try:
    var p = Path("testfile")
    p.write_text("test passes")
    if p.exists():
        var contents = p.read_text()
        print(contents) # test passes
except e:
    print(e)

Returns:

String: Contents of file as string.

Raises:

If the operation fails.

read_bytes

read_bytes(self) -> List[Byte]

Returns content of the file as bytes.

Examples:

from pathlib import Path

try:
    var p = Path("testfile")
    p.write_text("test passes")
    if p.exists():
        var contents = p.read_bytes()
        assert_true(contents[0] == 116)
except e:
    print(e)

Returns:

List: Contents of file as list of bytes.

Raises:

If the operation fails.

write_text

write_text[T: Writable](self, value: T)

Writes the value to the file as text.

Examples:

from pathlib import Path

try:
    var p = Path("testfile")
    p.write_text("test passes")
    if p.exists():
        var contents = p.read_text()
        print(contents) # test passes
except e:
    print(e)

Parameters:

  • T (Writable): The type of an object conforming to the Writable trait.

Args:

  • value (T): The value to write.

Raises:

If the operation fails.

write_bytes

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

Writes bytes to the file.

Examples:

from pathlib import Path

try:
    var p = Path("testfile")
    var s = "Hello"
    p.write_bytes(s.as_bytes())
    if p.exists():
        var contents = p.read_text()
        print(contents) # Hello
except e:
    print(e)

Args:

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

Raises:

If the operation fails.

suffix

suffix(self) -> String

The path's extension, if any. This includes the leading period. For example: '.txt'. If no extension is found, returns the empty string.

Examples:

from pathlib import Path

try:
    var p = Path("testfile.txt")
    print(p.suffix())
    assert_true(p.suffix() == ".txt")
except e:
    print(e)

Returns:

String: The path's extension.

joinpath

joinpath(self, *pathsegments: String) -> Self

Joins the Path using the pathsegments.

Examples:

from pathlib import Path
from tempfile import gettempdir

var p = Path(gettempdir().or_else("/tmp/")) # Both end with trailing /
var path = p.joinpath("intermediate/") # Trailing / for intermediate
path = path.joinpath("tempfile.txt")   # No / for file name
print(path) # legal path

Args:

  • *pathsegments (String): The path segments.

Returns:

Self: The path concatenation with the pathsegments using the directory separator.

listdir

listdir(self) -> List[Path]

Gets the list of entries contained in the path provided.

Examples:

from pathlib import Path, cwd

try:
    for item in cwd().listdir():
        print(item) # each item name in working directory
except e:
    print(e)

Returns:

List: The list of entries in the path provided.

Raises:

If the operation fails.

name

name(self) -> String

Returns the name of the path.

Examples:

from pathlib import Path

Path("a/path/foo.txt").name()  # returns "foo.txt"

Returns:

String: The name of the path.

parts

parts(self) -> List[StringSlice[origin_of(self.path)]]

Returns the parts of the path separated by DIR_SEPARATOR.

Examples:

from pathlib import Path

for p in Path("a/path/foo.txt").parts():
    print(p) # a, path, foo.txt

Returns:

List: The parts of the path separated by DIR_SEPARATOR.

Was this page helpful?