Skip to content

Kpath


File: filesystem/kpath.py

The pathlib.Path class is commonly used for file and directory operations in Python. To provide a consistent interface for file system operations, that does not use exceptions, a wrapper class is created called KPath. This class wraps the pathlib.Path class and provides methods for file and directory operations, such as creating directories, reading and writing files, and checking file existence. The KPath class also provides a way to set file permissions using the FilesystemModes enum.

The interface of the KPath class is kept very similar to the pathlib.Path class to enable a drop-in replacement. Therefore, the migration to the KPath class is straightforward.

The class uses the DCHECK_ functions from the base.log.check module to do any argument checks. To disable the checks, the -O flag needs to be set when running the Python interpreter.

Classes:

  • FilesystemModes

    Enum for file and directory permissions.

  • KPath

    Path class that wraps pathlib.Path and returns status objects instead of raising exceptions.

FilesystemModes

Bases: IntEnum

Enum for file and directory permissions.

Attributes:

  • ALL_RWX

    Full permissions (read, write, execute) for owner, group, and others

  • ALL_RW

    Read and write permissions for owner, group, and others

  • OWNER_RWX_OTHERS_RX

    Owner has full permissions, group and others can read/execute

  • ONLY_OWNER_RWX

    Owner has full permissions, no permissions for group or others

  • OWNER_RW_OTHERS_R

    Owner can read/write, group and others can only read

  • ONLY_OWNER_RW

    Owner can read/write, no permissions for group or others

  • ALL_R

    Read-only permissions for owner, group, and others

  • ONLY_OWNER_R

    Read-only permissions for owner only

  • OWNER_RWX_GROUP_RX

    Owner has full permissions, group can read/execute, others have no permissions

  • OWNER_GROUP_RWX

    Owner and group have full permissions, others have no permissions

Source code in kern_comm_lib/filesystem/kpath.py
class FilesystemModes(enum.IntEnum):
  """Enum for file and directory permissions."""

  ALL_RWX = 0o777
  """Full permissions (read, write, execute) for owner, group, and others"""
  ALL_RW = 0o666
  """Read and write permissions for owner, group, and others"""
  OWNER_RWX_OTHERS_RX = 0o755
  """Owner has full permissions, group and others can read/execute"""
  ONLY_OWNER_RWX = 0o700
  """Owner has full permissions, no permissions for group or others"""
  OWNER_RW_OTHERS_R = 0o644
  """Owner can read/write, group and others can only read"""
  ONLY_OWNER_RW = 0o600
  """Owner can read/write, no permissions for group or others"""
  ALL_R = 0o444
  """Read-only permissions for owner, group, and others"""
  ONLY_OWNER_R = 0o400
  """Read-only permissions for owner only"""
  OWNER_RWX_GROUP_RX = 0o750
  """Owner has full permissions, group can read/execute, others have no permissions"""
  OWNER_GROUP_RWX = 0o770
  """Owner and group have full permissions, others have no permissions"""

ALL_RWX class-attribute instance-attribute

ALL_RWX = 511

Full permissions (read, write, execute) for owner, group, and others

ALL_RW class-attribute instance-attribute

ALL_RW = 438

Read and write permissions for owner, group, and others

OWNER_RWX_OTHERS_RX class-attribute instance-attribute

OWNER_RWX_OTHERS_RX = 493

Owner has full permissions, group and others can read/execute

ONLY_OWNER_RWX class-attribute instance-attribute

ONLY_OWNER_RWX = 448

Owner has full permissions, no permissions for group or others

OWNER_RW_OTHERS_R class-attribute instance-attribute

OWNER_RW_OTHERS_R = 420

Owner can read/write, group and others can only read

ONLY_OWNER_RW class-attribute instance-attribute

ONLY_OWNER_RW = 384

Owner can read/write, no permissions for group or others

ALL_R class-attribute instance-attribute

ALL_R = 292

Read-only permissions for owner, group, and others

ONLY_OWNER_R class-attribute instance-attribute

ONLY_OWNER_R = 256

Read-only permissions for owner only

OWNER_RWX_GROUP_RX class-attribute instance-attribute

OWNER_RWX_GROUP_RX = 488

Owner has full permissions, group can read/execute, others have no permissions

OWNER_GROUP_RWX class-attribute instance-attribute

OWNER_GROUP_RWX = 504

Owner and group have full permissions, others have no permissions

KPath

Path class that wraps pathlib.Path and returns status objects instead of raising exceptions.

Methods:

  • __init__

    Constructor.

  • __str__

    Returns the string representation of the path.

  • __repr__

    Returns the representation of the path.

  • exists

    Checks if the path exists.

  • is_file

    Checks if the path is a file.

  • is_dir

    Checks if the path is a directory.

  • mkdir

    Creates a directory at this path.

  • rmdir

    Removes this directory.

  • touch

    Creates a file at this path.

  • unlink

    Removes this file or symbolic link.

  • read_bytes

    Reads bytes from this file.

  • read_text

    Reads text from this file.

  • write_bytes

    Writes bytes to this file.

  • write_text

    Writes text to this file.

  • iterdir

    Iterates over the files in this directory.

Attributes:

  • path (Path) –

    Gets the underlying pathlib.Path object.

  • name (str) –

    Gets the name of the file or directory.

  • parent (KPath) –

    Gets the parent directory as KPath.

  • suffix (str) –

    Gets the file extension.

  • stem (str) –

    Gets the filename without extension.

Source code in kern_comm_lib/filesystem/kpath.py
class KPath:
  """Path class that wraps pathlib.Path and returns status objects instead of raising exceptions."""

  def __init__(self, a_path: Union[str, pathlib.Path, "KPath"]) -> None:
    """Constructor.

    Args:
      a_path: The path to wrap. Can be a string, pathlib.Path, or another KPath object.
    """
    # <editor-fold desc="Checks">
    kern.DCHECK_NOT_NONE(a_path)
    # </editor-fold>
    # If the path is a string or a KPath object, it has to be converted
    # to a pathlib.Path object because KPath is a wrapper around pathlib.Path.
    if isinstance(a_path, str):
      self._path: pathlib.Path = pathlib.Path(a_path)
    elif isinstance(a_path, KPath):
      self._path: pathlib.Path = pathlib.Path(a_path.path)
    else:
      self._path: pathlib.Path = a_path

  # <editor-fold desc="Magic methods">
  def __str__(self) -> str:
    """Returns the string representation of the path.

    Returns:
      The string representation of the path.
    """
    return str(self._path)

  def __repr__(self) -> str:
    """Returns the representation of the path.

    Returns:
      The representation of the path.
    """
    return f"KPath({repr(self._path)})"

  # </editor-fold>

  # <editor-fold desc="Getter methods">
  @property
  def path(self) -> pathlib.Path:
    """Gets the underlying pathlib.Path object.

    Returns:
      The underlying pathlib.Path object.
    """
    return self._path

  @property
  def name(self) -> str:
    """Gets the name of the file or directory.

    Returns:
      The name of the file or directory
    """
    return self._path.name

  @property
  def parent(self) -> "KPath":
    """Gets the parent directory as KPath.

    Returns:
      The parent directory as a KPath object.
    """
    return KPath(self._path.parent)

  @property
  def suffix(self) -> str:
    """Gets the file extension.

    Returns:
      The file extension.
    """
    return self._path.suffix

  @property
  def stem(self) -> str:
    """Gets the filename without extension.

    Returns:
      The filename without extension.
    """
    return self._path.stem

  # </editor-fold>

  def exists(self) -> kern.AStatusOrElse[bool]:
    """Checks if the path exists.

    Returns:
      Either True if the path exists or False if it doesn't, otherwise a Status object containing an error status.
    """
    try:
      return self._path.exists()
    except Exception as e:
      return kern.Status.from_exception(e)

  def is_file(self) -> kern.AStatusOrElse[bool]:
    """Checks if the path is a file.

    Returns:
      Either True if the path is a file or False if it doesn't, otherwise a Status object containing an error status.
    """
    try:
      return self._path.is_file()
    except Exception as e:
      return kern.Status.from_exception(e)

  def is_dir(self) -> kern.AStatusOrElse[bool]:
    """Checks if the path is a directory.

    Returns:
      Either True if the path is a directory or False if it doesn't, otherwise a Status object containing an error status.
    """
    try:
      return self._path.is_dir()
    except Exception as e:
      return kern.Status.from_exception(e)

  # Path operations

  def mkdir(
      self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False
  ) -> kern.Status:
    """Creates a directory at this path.

    Args:
      mode (default: 0o777): The mode for the new directory (default is 0o777).
      parents (default: False): If True, create parent directories as needed (default is False).
      exist_ok (default: False): If True, do not raise an error if the directory already exists (default is False).

    Returns:
        A Status object indicating success or failure.
    """
    # <editor-fold desc="Checks">
    kern.DCHECK_NOT_NONE(mode)
    kern.DCHECK_IN_ENUM(mode, FilesystemModes)
    kern.DCHECK_NOT_NONE(parents)
    kern.DCHECK_NOT_NONE(exist_ok)
    # </editor-fold>
    try:
      self._path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
      return kern.Status()
    except FileExistsError:
      return kern.Status.from_status_code(
          kern.StatusCode.ALREADY_EXISTS,
          f"Directory already exists: {self._path}",
      )
    except Exception as e:
      return kern.Status.from_exception(e)

  def rmdir(self, recursive: bool = False) -> kern.Status:
    """Removes this directory.

    Args:
        recursive (default: False): If True, removes directory with all its contents. If False, directory must be empty.

    Returns:
      Status object indicating success or failure.
    """
    # <editor-fold desc="Checks">
    kern.DCHECK_NOT_NONE(recursive)
    # </editor-fold>

    try:
      if recursive:
        shutil.rmtree(str(self._path))
      else:
        self._path.rmdir()
      return kern.Status()
    except FileNotFoundError:
      return kern.status.not_found_error(f"Directory not found: {self._path}")
    except Exception as e:
      return kern.Status.from_exception(e)

  def touch(self, mode: int = 0o666, exist_ok: bool = True) -> kern.Status:
    """Creates a file at this path.

    Args:
        mode: The mode for the new file (default is 0o666).
        exist_ok (default: True): If True, do not raise an error if the file already exists.

    Returns:
      Status object indicating success or failure.
    """
    # <editor-fold desc="Checks">
    kern.DCHECK_NOT_NONE(mode)
    kern.DCHECK_IN_ENUM(mode, FilesystemModes)
    kern.DCHECK_NOT_NONE(exist_ok)
    # </editor-fold>
    try:
      self._path.touch(mode=mode, exist_ok=exist_ok)
      return kern.Status()
    except Exception as e:
      return kern.Status.from_exception(e)

  def unlink(self, missing_ok: bool = False) -> kern.Status:
    """Removes this file or symbolic link.

    Args:
        missing_ok (default: False): If True, do not raise an error if the file does not exist.

    Returns:
      Status object indicating success or failure.
    """
    # <editor-fold desc="Checks">
    kern.DCHECK_NOT_NONE(missing_ok)
    # </editor-fold>
    try:
      self._path.unlink(missing_ok=missing_ok)
      return kern.Status()
    except FileNotFoundError:
      if missing_ok:
        return kern.Status()
      return kern.status.not_found_error(f"File not found: {self._path}")
    except Exception as e:
      return kern.Status.from_exception(e)

  # File content operations

  def read_bytes(self) -> kern.AStatusOrElse[bytes]:
    """Reads bytes from this file.

    Returns:
      Either a bytes object or a Status object containing an error status.
    """
    try:
      return self._path.read_bytes()
    except FileNotFoundError:
      return kern.status.not_found_error(f"File not found: {self._path}")
    except Exception as e:
      return kern.Status.from_exception(e)

  def read_text(
      self, encoding: str = "utf-8", errors: str | None = None
  ) -> kern.AStatusOrElse[str]:
    """Reads text from this file.

    Args:
      encoding (default: utf-8): The encoding to use.
      errors (default: None): How to handle encoding errors.

    Returns:
      Either a string of text or a Status object containing an error status.
    """
    # <editor-fold desc="Checks">
    kern.DCHECK_NOT_NONE(encoding)
    kern.DCHECK_NOT_EQ(encoding, "")
    # TODO: Add check for the errors argument! Is an empty string valid?
    # </editor-fold>
    try:
      return self._path.read_text(encoding=encoding, errors=errors)
    except FileNotFoundError:
      return kern.status.not_found_error(f"File not found: {self._path}")
    except Exception as e:
      return kern.Status.from_exception(e)

  def write_bytes(self, data: bytes) -> kern.Status:
    """Writes bytes to this file.

    Args:
      data: The data in bytes to write.

    Returns:
      A Status object indicating success or failure.
    """
    # <editor-fold desc="Checks">
    kern.DCHECK_NOT_NONE(data)
    # </editor-fold>
    try:
      self._path.write_bytes(data)
      return kern.Status()
    except Exception as e:
      return kern.Status.from_exception(e)

  def write_text(
      self, data: str, encoding: str = "utf-8", errors: str | None = None
  ) -> kern.Status:
    """Writes text to this file.

    Args:
      data: The data as text to write.
      encoding (default: utf-8): The encoding to use.
      errors (default: None): How to handle encoding errors.

    Returns:
      A Status object indicating success or failure.
    """
    # <editor-fold desc="Checks">
    kern.DCHECK_NOT_NONE(data)
    kern.DCHECK_NOT_NONE(encoding)
    kern.DCHECK_NOT_EQ(encoding, "")
    # TODO: Add check for the errors argument! Is an empty string valid?
    # </editor-fold>
    try:
      self._path.write_text(data, encoding=encoding, errors=errors)
      return kern.Status()
    except Exception as e:
      return kern.Status.from_exception(e)

  # Directory operations

  def iterdir(self) -> kern.AStatusOrElse[list["KPath"]]:
    """Iterates over the files in this directory.

    Returns:
      Either a Python list of KPath objects or a Status object containing an error status.
    """
    try:
      return [KPath(path) for path in self._path.iterdir()]
    except FileNotFoundError:
      return kern.status.not_found_error(f"Directory not found: {self._path}")
    except NotADirectoryError:
      return kern.status.invalid_argument_error(
          f"Not a directory: {self._path}"
      )
    except Exception as e:
      return kern.Status.from_exception(e)

path property

path: Path

Gets the underlying pathlib.Path object.

Returns:

  • Path

    The underlying pathlib.Path object.

name property

name: str

Gets the name of the file or directory.

Returns:

  • str

    The name of the file or directory

parent property

parent: KPath

Gets the parent directory as KPath.

Returns:

  • KPath

    The parent directory as a KPath object.

suffix property

suffix: str

Gets the file extension.

Returns:

  • str

    The file extension.

stem property

stem: str

Gets the filename without extension.

Returns:

  • str

    The filename without extension.

__init__

__init__(a_path: Union[str, Path, KPath]) -> None

Constructor.

Parameters:

  • a_path (Union[str, Path, KPath]) –

    The path to wrap. Can be a string, pathlib.Path, or another KPath object.

Source code in kern_comm_lib/filesystem/kpath.py
def __init__(self, a_path: Union[str, pathlib.Path, "KPath"]) -> None:
  """Constructor.

  Args:
    a_path: The path to wrap. Can be a string, pathlib.Path, or another KPath object.
  """
  # <editor-fold desc="Checks">
  kern.DCHECK_NOT_NONE(a_path)
  # </editor-fold>
  # If the path is a string or a KPath object, it has to be converted
  # to a pathlib.Path object because KPath is a wrapper around pathlib.Path.
  if isinstance(a_path, str):
    self._path: pathlib.Path = pathlib.Path(a_path)
  elif isinstance(a_path, KPath):
    self._path: pathlib.Path = pathlib.Path(a_path.path)
  else:
    self._path: pathlib.Path = a_path

__str__

__str__() -> str

Returns the string representation of the path.

Returns:

  • str

    The string representation of the path.

Source code in kern_comm_lib/filesystem/kpath.py
def __str__(self) -> str:
  """Returns the string representation of the path.

  Returns:
    The string representation of the path.
  """
  return str(self._path)

__repr__

__repr__() -> str

Returns the representation of the path.

Returns:

  • str

    The representation of the path.

Source code in kern_comm_lib/filesystem/kpath.py
def __repr__(self) -> str:
  """Returns the representation of the path.

  Returns:
    The representation of the path.
  """
  return f"KPath({repr(self._path)})"

exists

exists() -> kern.AStatusOrElse[bool]

Checks if the path exists.

Returns:

  • AStatusOrElse[bool]

    Either True if the path exists or False if it doesn't, otherwise a Status object containing an error status.

Source code in kern_comm_lib/filesystem/kpath.py
def exists(self) -> kern.AStatusOrElse[bool]:
  """Checks if the path exists.

  Returns:
    Either True if the path exists or False if it doesn't, otherwise a Status object containing an error status.
  """
  try:
    return self._path.exists()
  except Exception as e:
    return kern.Status.from_exception(e)

is_file

is_file() -> kern.AStatusOrElse[bool]

Checks if the path is a file.

Returns:

  • AStatusOrElse[bool]

    Either True if the path is a file or False if it doesn't, otherwise a Status object containing an error status.

Source code in kern_comm_lib/filesystem/kpath.py
def is_file(self) -> kern.AStatusOrElse[bool]:
  """Checks if the path is a file.

  Returns:
    Either True if the path is a file or False if it doesn't, otherwise a Status object containing an error status.
  """
  try:
    return self._path.is_file()
  except Exception as e:
    return kern.Status.from_exception(e)

is_dir

is_dir() -> kern.AStatusOrElse[bool]

Checks if the path is a directory.

Returns:

  • AStatusOrElse[bool]

    Either True if the path is a directory or False if it doesn't, otherwise a Status object containing an error status.

Source code in kern_comm_lib/filesystem/kpath.py
def is_dir(self) -> kern.AStatusOrElse[bool]:
  """Checks if the path is a directory.

  Returns:
    Either True if the path is a directory or False if it doesn't, otherwise a Status object containing an error status.
  """
  try:
    return self._path.is_dir()
  except Exception as e:
    return kern.Status.from_exception(e)

mkdir

mkdir(mode: int = 511, parents: bool = False, exist_ok: bool = False) -> kern.Status

Creates a directory at this path.

Parameters:

  • mode (default, default: 511 ) –

    0o777): The mode for the new directory (default is 0o777).

  • parents (default, default: False ) –

    False): If True, create parent directories as needed (default is False).

  • exist_ok (default, default: False ) –

    False): If True, do not raise an error if the directory already exists (default is False).

Returns:

  • Status

    A Status object indicating success or failure.

Source code in kern_comm_lib/filesystem/kpath.py
def mkdir(
    self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False
) -> kern.Status:
  """Creates a directory at this path.

  Args:
    mode (default: 0o777): The mode for the new directory (default is 0o777).
    parents (default: False): If True, create parent directories as needed (default is False).
    exist_ok (default: False): If True, do not raise an error if the directory already exists (default is False).

  Returns:
      A Status object indicating success or failure.
  """
  # <editor-fold desc="Checks">
  kern.DCHECK_NOT_NONE(mode)
  kern.DCHECK_IN_ENUM(mode, FilesystemModes)
  kern.DCHECK_NOT_NONE(parents)
  kern.DCHECK_NOT_NONE(exist_ok)
  # </editor-fold>
  try:
    self._path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
    return kern.Status()
  except FileExistsError:
    return kern.Status.from_status_code(
        kern.StatusCode.ALREADY_EXISTS,
        f"Directory already exists: {self._path}",
    )
  except Exception as e:
    return kern.Status.from_exception(e)

rmdir

rmdir(recursive: bool = False) -> kern.Status

Removes this directory.

Parameters:

  • recursive (default, default: False ) –

    False): If True, removes directory with all its contents. If False, directory must be empty.

Returns:

  • Status

    Status object indicating success or failure.

Source code in kern_comm_lib/filesystem/kpath.py
def rmdir(self, recursive: bool = False) -> kern.Status:
  """Removes this directory.

  Args:
      recursive (default: False): If True, removes directory with all its contents. If False, directory must be empty.

  Returns:
    Status object indicating success or failure.
  """
  # <editor-fold desc="Checks">
  kern.DCHECK_NOT_NONE(recursive)
  # </editor-fold>

  try:
    if recursive:
      shutil.rmtree(str(self._path))
    else:
      self._path.rmdir()
    return kern.Status()
  except FileNotFoundError:
    return kern.status.not_found_error(f"Directory not found: {self._path}")
  except Exception as e:
    return kern.Status.from_exception(e)

touch

touch(mode: int = 438, exist_ok: bool = True) -> kern.Status

Creates a file at this path.

Parameters:

  • mode (int, default: 438 ) –

    The mode for the new file (default is 0o666).

  • exist_ok (default, default: True ) –

    True): If True, do not raise an error if the file already exists.

Returns:

  • Status

    Status object indicating success or failure.

Source code in kern_comm_lib/filesystem/kpath.py
def touch(self, mode: int = 0o666, exist_ok: bool = True) -> kern.Status:
  """Creates a file at this path.

  Args:
      mode: The mode for the new file (default is 0o666).
      exist_ok (default: True): If True, do not raise an error if the file already exists.

  Returns:
    Status object indicating success or failure.
  """
  # <editor-fold desc="Checks">
  kern.DCHECK_NOT_NONE(mode)
  kern.DCHECK_IN_ENUM(mode, FilesystemModes)
  kern.DCHECK_NOT_NONE(exist_ok)
  # </editor-fold>
  try:
    self._path.touch(mode=mode, exist_ok=exist_ok)
    return kern.Status()
  except Exception as e:
    return kern.Status.from_exception(e)
unlink(missing_ok: bool = False) -> kern.Status

Removes this file or symbolic link.

Parameters:

  • missing_ok (default, default: False ) –

    False): If True, do not raise an error if the file does not exist.

Returns:

  • Status

    Status object indicating success or failure.

Source code in kern_comm_lib/filesystem/kpath.py
def unlink(self, missing_ok: bool = False) -> kern.Status:
  """Removes this file or symbolic link.

  Args:
      missing_ok (default: False): If True, do not raise an error if the file does not exist.

  Returns:
    Status object indicating success or failure.
  """
  # <editor-fold desc="Checks">
  kern.DCHECK_NOT_NONE(missing_ok)
  # </editor-fold>
  try:
    self._path.unlink(missing_ok=missing_ok)
    return kern.Status()
  except FileNotFoundError:
    if missing_ok:
      return kern.Status()
    return kern.status.not_found_error(f"File not found: {self._path}")
  except Exception as e:
    return kern.Status.from_exception(e)

read_bytes

read_bytes() -> kern.AStatusOrElse[bytes]

Reads bytes from this file.

Returns:

  • AStatusOrElse[bytes]

    Either a bytes object or a Status object containing an error status.

Source code in kern_comm_lib/filesystem/kpath.py
def read_bytes(self) -> kern.AStatusOrElse[bytes]:
  """Reads bytes from this file.

  Returns:
    Either a bytes object or a Status object containing an error status.
  """
  try:
    return self._path.read_bytes()
  except FileNotFoundError:
    return kern.status.not_found_error(f"File not found: {self._path}")
  except Exception as e:
    return kern.Status.from_exception(e)

read_text

read_text(encoding: str = 'utf-8', errors: str | None = None) -> kern.AStatusOrElse[str]

Reads text from this file.

Parameters:

  • encoding (default, default: 'utf-8' ) –

    utf-8): The encoding to use.

  • errors (default, default: None ) –

    None): How to handle encoding errors.

Returns:

  • AStatusOrElse[str]

    Either a string of text or a Status object containing an error status.

Source code in kern_comm_lib/filesystem/kpath.py
def read_text(
    self, encoding: str = "utf-8", errors: str | None = None
) -> kern.AStatusOrElse[str]:
  """Reads text from this file.

  Args:
    encoding (default: utf-8): The encoding to use.
    errors (default: None): How to handle encoding errors.

  Returns:
    Either a string of text or a Status object containing an error status.
  """
  # <editor-fold desc="Checks">
  kern.DCHECK_NOT_NONE(encoding)
  kern.DCHECK_NOT_EQ(encoding, "")
  # TODO: Add check for the errors argument! Is an empty string valid?
  # </editor-fold>
  try:
    return self._path.read_text(encoding=encoding, errors=errors)
  except FileNotFoundError:
    return kern.status.not_found_error(f"File not found: {self._path}")
  except Exception as e:
    return kern.Status.from_exception(e)

write_bytes

write_bytes(data: bytes) -> kern.Status

Writes bytes to this file.

Parameters:

  • data (bytes) –

    The data in bytes to write.

Returns:

  • Status

    A Status object indicating success or failure.

Source code in kern_comm_lib/filesystem/kpath.py
def write_bytes(self, data: bytes) -> kern.Status:
  """Writes bytes to this file.

  Args:
    data: The data in bytes to write.

  Returns:
    A Status object indicating success or failure.
  """
  # <editor-fold desc="Checks">
  kern.DCHECK_NOT_NONE(data)
  # </editor-fold>
  try:
    self._path.write_bytes(data)
    return kern.Status()
  except Exception as e:
    return kern.Status.from_exception(e)

write_text

write_text(data: str, encoding: str = 'utf-8', errors: str | None = None) -> kern.Status

Writes text to this file.

Parameters:

  • data (str) –

    The data as text to write.

  • encoding (default, default: 'utf-8' ) –

    utf-8): The encoding to use.

  • errors (default, default: None ) –

    None): How to handle encoding errors.

Returns:

  • Status

    A Status object indicating success or failure.

Source code in kern_comm_lib/filesystem/kpath.py
def write_text(
    self, data: str, encoding: str = "utf-8", errors: str | None = None
) -> kern.Status:
  """Writes text to this file.

  Args:
    data: The data as text to write.
    encoding (default: utf-8): The encoding to use.
    errors (default: None): How to handle encoding errors.

  Returns:
    A Status object indicating success or failure.
  """
  # <editor-fold desc="Checks">
  kern.DCHECK_NOT_NONE(data)
  kern.DCHECK_NOT_NONE(encoding)
  kern.DCHECK_NOT_EQ(encoding, "")
  # TODO: Add check for the errors argument! Is an empty string valid?
  # </editor-fold>
  try:
    self._path.write_text(data, encoding=encoding, errors=errors)
    return kern.Status()
  except Exception as e:
    return kern.Status.from_exception(e)

iterdir

iterdir() -> kern.AStatusOrElse[list[KPath]]

Iterates over the files in this directory.

Returns:

  • AStatusOrElse[list[KPath]]

    Either a Python list of KPath objects or a Status object containing an error status.

Source code in kern_comm_lib/filesystem/kpath.py
def iterdir(self) -> kern.AStatusOrElse[list["KPath"]]:
  """Iterates over the files in this directory.

  Returns:
    Either a Python list of KPath objects or a Status object containing an error status.
  """
  try:
    return [KPath(path) for path in self._path.iterdir()]
  except FileNotFoundError:
    return kern.status.not_found_error(f"Directory not found: {self._path}")
  except NotADirectoryError:
    return kern.status.invalid_argument_error(
        f"Not a directory: {self._path}"
    )
  except Exception as e:
    return kern.Status.from_exception(e)