Skip to content

API reference#

earthcarekit.utils.path

Filesystem path utilities.

Notes#

This module does not depend on other internal modules.


ensure_dir #

ensure_dir(path: PathLike) -> None

Create directory if not existing

Source code in earthcarekit/utils/path.py
def ensure_dir(path: PathLike) -> None:
    """Create directory if not existing"""
    _path = Path(path)
    if not os.path.exists(_path):
        os.mkdir(_path)

ensure_file #

ensure_file(path: PathLike) -> None

Create file if not existing

Source code in earthcarekit/utils/path.py
def ensure_file(path: PathLike) -> None:
    """Create file if not existing"""
    _path = Path(path)
    _path.parent.mkdir(parents=True, exist_ok=True)
    _path.touch(exist_ok=True)

extend_filepath #

extend_filepath(filepath: PathLike, suffix: str) -> str

Appends a suffix to the filename before its extension.

Parameters:

Name Type Description Default
filepath PathLike

Absolute file path.

required
suffix str

String to append to the filename.

required

Returns:

Type Description
str

New file path with the suffix added.

Source code in earthcarekit/utils/path.py
def extend_filepath(filepath: PathLike, suffix: str) -> str:
    """Appends a suffix to the filename before its extension.

    Args:
        filepath: Absolute file path.
        suffix: String to append to the filename.

    Returns:
        New file path with the suffix added.
    """

    p = Path(os.path.abspath(str(filepath)))
    return str(p.with_name(f"{p.stem}{suffix}{p.suffix}"))

search_files_by_regex #

search_files_by_regex(root: PathLike, pattern: str) -> list[str]

Recursively searches for files matching a regex pattern.

Parameters:

Name Type Description Default
root PathLike

Root directory to search.

required
pattern str

Regular expression pattern to match filenames.

required

Returns:

Type Description
list[str]

Absolute paths to matching files.

Raises:

Type Description
FileNotFoundError

If root does not exist.

error

If pattern is invalid.

Source code in earthcarekit/utils/path.py
def search_files_by_regex(root: PathLike, pattern: str) -> list[str]:
    """Recursively searches for files matching a regex pattern.

    Args:
        root: Root directory to search.
        pattern: Regular expression pattern to match filenames.

    Returns:
        Absolute paths to matching files.

    Raises:
        FileNotFoundError: If `root` does not exist.
        re.error: If `pattern` is invalid.
    """
    root = str(root)
    if not os.path.exists(root):
        raise FileNotFoundError(
            f"{search_files_by_regex.__name__}() Root directory does not exist: {root}"
        )

    filepaths = []
    for dirpath, _, filenames in os.walk(root):
        for filename in filenames:
            filepath = os.path.join(dirpath, filename)
            if re.search(pattern, filename):
                filepaths.append(filepath)
    return filepaths