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 = True
Methods
__init__
__init__(out self)
Initializes a path with the current directory.
Raises:
If the operation fails.
__init__(out self, path: StringSlice[path.origin])
Initializes a path with the provided path.
Args:
- path (
StringSlice): The file system path.
@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[path.value])
Initializes a path with the provided path.
Args:
- path (
StringLiteral): The file system path.
__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[other.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[suffix.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[suffix.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.
Example:
from pathlib import Path
var p = Path() # Path to cwd
print(p.stat()) # os.stat_result(...)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.
Example:
from pathlib import Path
var p = Path("./path/to/nowhere/does-not-exist")
print("Exists" if p.exists() else "Does not exist") # Does not existReturns:
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.
Example:
from pathlib import Path
from testing import assert_true
var p = Path("~")
assert_true(p.expanduser() == Path.home())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 ~.
Example:
from pathlib import Path
from testing import assert_true
var p = Path("~")
assert_true(p.expanduser() == Path.home())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.
Example:
from pathlib import Path
from testing import assert_false
var p = Path.home()
assert_true(p.is_dir())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.
Example:
from pathlib import Path
from testing import assert_false
var p = Path.home()
assert_false(p.is_file())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.
Example:
from pathlib import Path
var p = Path("testfile.txt")
p.write_text("Hello Mojo")
if p.exists():
var contents = p.read_text()
print(contents) # Hello MojoReturns:
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.
Example:
from pathlib import Path
from testing import assert_true
var p = Path("testfile.txt")
p.write_text("test")
if p.exists():
var contents = p.read_bytes()
assert_true(contents[0] == 116)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.
Example:
from pathlib import Path
var p = Path("testfile")
p.write_text("Hello")
if p.exists():
var contents = p.read_text()
print(contents) # HelloParameters:
- T (
Writable): The type of an object conforming to theWritabletrait.
Args:
- value (
T): The value to write.
Raises:
If the operation fails.
write_bytes
write_bytes(self, bytes: Span[Byte, bytes.origin])
Writes bytes to the file.
Example:
from pathlib import Path
var p = Path("testfile")
var s = "Hello"
p.write_bytes(s.as_bytes())
if p.exists():
var contents = p.read_text()
print(contents) # HelloArgs:
- 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.
Example:
from pathlib import Path
from testing import assert_true
var p = Path("testfile.txt")
print(p.suffix())
assert_true(p.suffix() == ".txt")
p = Path(".hiddenfile")
assert_true(p.suffix() == "") # No suffixReturns:
String: The path's extension.
joinpath
joinpath(self, *pathsegments: String) -> Self
Joins the Path using the pathsegments.
Example:
from pathlib import Path
from tempfile import gettempdir
from testing import assert_true
# gettmpdir() has no guarantee of trailing /
# Use joinpath to ensure path construction
var p = Path("/tmp")
p = p.joinpath("testdir") # No trailing /
p = p.joinpath("testfile.txt")
assert_true(p == Path("/tmp/testdir/testfile.txt"))
p = Path("/tmp/")
p = p.joinpath("testdir/") # Trailing /
p = p.joinpath("testfile.txt")
assert_true(p == Path("/tmp/testdir/testfile.txt"))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.
Example:
from pathlib import Path, cwd
for item in cwd().listdir():
print(item) # each item name in working directoryReturns:
List: The list of entries in the path provided.
Raises:
If the operation fails.
name
name(self) -> String
Returns the name of the path.
Example:
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.
Example:
from pathlib import Path
from testing import assert_true
for p, q in zip(Path("a/path/foo.txt").parts(), ["a", "path", "foo.txt"]):
assert_true(p == q)Returns:
List: The parts of the path separated by DIR_SEPARATOR.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!