os_helper.path_utils module

Path Utilities

This module provides helper functions for handling and manipulating file and directory paths. Functions include checking existence, converting between absolute and relative paths, formatting paths, and performing file operations like copying and removing files/directories.

Author:
os_helper.path_utils.absolute2relative_path(path, base_path=None)[source]

Convert a path to a relative path expressed from base_path.

Parameters:
  • path (str) – The path to convert (absolute or relative).

  • base_path (str, optional) – Reference path. Defaults to the current working directory.

Returns:

The relative path from base_path to path.

Return type:

str

Example

>>> absolute2relative_path("/home/user/project/file.txt", "/home/user")
'project/file.txt'
os_helper.path_utils.checkfile(filepath, msg='', check_empty=False)[source]

Assert that a file exists and, optionally, that it is non-empty.

Parameters:
  • filepath (str) – The path to the file.

  • msg (str, optional) – Prefix added to the assertion message on failure.

  • check_empty (bool, optional) – If True, also asserts that the file size is greater than zero.

Raises:

AssertionError – If the file does not exist (or is empty when check_empty is True).

Return type:

None

Example

>>> checkfile("data.csv", msg="Data file missing", check_empty=True)
os_helper.path_utils.copyfile(source, destination)[source]

Copy a file from source to destination, preserving metadata.

If destination is an existing directory, the source file name is appended to it (mirroring cp semantics).

Parameters:
  • source (str) – The path to the source file (must exist and be non-empty).

  • destination (str) – The path to the destination file or existing directory.

Raises:
  • AssertionError – If the source file does not exist or is empty, or if source and destination resolve to the same path.

  • OSError – If the underlying shutil.copy2 call fails (propagated as-is).

Return type:

None

Example

>>> copyfile("source.txt", "backup/source_backup.txt")
os_helper.path_utils.dir_exists(path, check_empty=False)[source]

Check if a directory exists, with an option to verify it’s not empty.

Parameters:
  • path (str) – The path to the directory.

  • check_empty (bool, optional) – If True, also checks that the directory is not empty (excluding hidden files). Defaults to False.

Returns:

True if the directory exists (and is not empty if check_empty is True), False otherwise.

Return type:

bool

Example

>>> dir_exists("/path/to/folder")
True
>>> dir_exists("/path/to/empty_folder", check_empty=True)
False
os_helper.path_utils.file_exists(file_path, check_empty=False)[source]

Check if a file exists, with an option to verify it’s not empty.

Parameters:
  • file_path (str) – The path to the file.

  • check_empty (bool, optional) – If True, also checks that the file is not empty. Defaults to False.

Returns:

True if the file exists (and is not empty if check_empty is True), False otherwise.

Return type:

bool

Example

>>> file_exists("example.txt")
True
>>> file_exists("empty.txt", check_empty=True)
False
os_helper.path_utils.folder_name_ext(path, checkpath=False)[source]

Decompose a file or folder path into (folder, basename, extension).

The split happens at the last dot in the basename, so multi-part suffixes like .tar.gz are not collapsed into one extension. Use "basename.extension" to recover the original file name.

Returns an empty extension for: - directories, - files whose basename contains no dot.

Parameters:
  • path (str) – The path to decompose. Resolved to an absolute path internally.

  • checkpath (bool, optional) – If True, asserts that the path exists on disk.

Returns:

(folder, basename, extension) where extension excludes the leading dot.

Return type:

tuple of (str, str, str)

Examples

>>> folder_name_ext("/path/to/file.txt")
('/path/to', 'file', 'txt')
>>> folder_name_ext("/path/to/archive.tar.gz")
('/path/to', 'archive.tar', 'gz')
>>> folder_name_ext("/path/to/folder")          # existing directory
('/path/to', 'folder', '')
os_helper.path_utils.join(*args)[source]

Join multiple path components into a single absolute, normalized path.

This is the canonical path-construction helper exposed by os_helper and replaces the older os_path_constructor function (removed in v1.1.0). It accepts either positional components or a single iterable.

Parameters:

*args (str) – The path components to join, or a single iterable of path components.

Returns:

The absolute, normalized path.

Return type:

str

Example

>>> join("folder1", "subfolder2", "file.txt")
'/home/user/project/folder1/subfolder2/file.txt'
>>> join(["folder1", "subfolder2", "file.txt"])
'/home/user/project/folder1/subfolder2/file.txt'
os_helper.path_utils.make_directory(folder_path, exist_ok=True)[source]

Create a directory (and missing parents), optionally tolerating prior existence.

Parameters:
  • folder_path (str) – The path to the directory to create.

  • exist_ok (bool, optional) – If True (the default), succeed silently when the directory already exists. If False, FileExistsError is raised in that case.

Raises:
  • OSError – If the directory cannot be created (propagated from os.makedirs).

  • AssertionError – If os.makedirs returned without error but the directory is still not visible on disk afterwards.

Return type:

None

Example

>>> make_directory("/path/to/new_folder")
os_helper.path_utils.path_without_home(path)[source]

Convert an absolute path to be relative to the user’s home directory by replacing the home path with ‘~’.

Parameters:

path (str) – The absolute path to convert.

Returns:

The path with the home directory replaced by ‘~’, if applicable.

Return type:

str

Example

>>> path_without_home("/home/user/project/file.txt")
'~/project/file.txt'
os_helper.path_utils.recursive_glob(root_dir, pattern)[source]

Recursively search for files matching a glob pattern under root_dir.

Each subdirectory is walked and the pattern applied in turn, so patterns like "*.txt" match in nested folders as well as at the top level.

Parameters:
  • root_dir (str) – The root directory to start searching from.

  • pattern (str) – The glob pattern to match against file names (e.g., "*.txt").

Returns:

File paths matching the pattern, in walk order.

Return type:

List[str]

Example

>>> recursive_glob("/home/user", "*.txt")
['/home/user/file1.txt', '/home/user/docs/file2.txt']
os_helper.path_utils.relative2absolute_path(path, checkpath=False)[source]

Convert a relative path to an absolute path.

Parameters:
  • path (str) – The relative or absolute path to convert.

  • checkpath (bool, optional) – If True, verifies that the resulting absolute path exists (as a file or directory). Defaults to False.

Returns:

The absolute path.

Return type:

str

Raises:

FileNotFoundError – If checkpath is True and the path does not exist.

Example

>>> relative2absolute_path("docs/readme.md")
'/home/user/project/docs/readme.md'
os_helper.path_utils.remove_directory(folder_path)[source]

Remove a directory and all its contents.

A missing directory is treated as a no-op (logged at INFO); any other failure from shutil.rmtree is propagated to the caller.

Parameters:

folder_path (str) – The path to the directory to remove.

Raises:

OSError – If the directory exists but cannot be removed (propagated from shutil.rmtree).

Return type:

None

Example

>>> remove_directory("/path/to/temp_folder")
os_helper.path_utils.remove_files(files_list)[source]

Remove a list of files on a best-effort basis.

Missing entries are skipped and individual removal failures are logged at ERROR level without aborting the rest of the batch. This function does not raise — if you need hard-fail-on-first semantics, call pathlib.Path(p).unlink() yourself.

Parameters:

files_list (List[str]) – A list of file paths to remove.

Return type:

None

Example

>>> remove_files(["temp1.txt", "temp2.log"])
os_helper.path_utils.size_file(filepath)[source]

Get the size of a file in bytes.

Parameters:

filepath (str) – The path to the file.

Returns:

The size of the file in bytes, or -1 if the file does not exist.

Return type:

int

Example

>>> size_file("example.txt")
1024