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:
Warith HARCHAOUI, https://linkedin.com/in/warith-harchaoui
- os_helper.path_utils.absolute2relative_path(path, base_path=None)[source]
Convert a path to a relative path expressed from
base_path.- Parameters:
- Returns:
The relative path from
base_pathtopath.- Return type:
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:
- Raises:
AssertionError – If the file does not exist (or is empty when
check_emptyis 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
sourcetodestination, preserving metadata.If
destinationis an existing directory, the source file name is appended to it (mirroringcpsemantics).- Parameters:
- 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.copy2call 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:
- Returns:
True if the directory exists (and is not empty if check_empty is True), False otherwise.
- Return type:
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:
- Returns:
True if the file exists (and is not empty if check_empty is True), False otherwise.
- Return type:
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.gzare 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:
- Returns:
(folder, basename, extension)whereextensionexcludes the leading dot.- Return type:
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_helperand replaces the olderos_path_constructorfunction (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:
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:
- Raises:
OSError – If the directory cannot be created (propagated from
os.makedirs).AssertionError – If
os.makedirsreturned 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:
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:
- 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:
- Returns:
The absolute path.
- Return type:
- 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.rmtreeis 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"])