standardize_path

pyhelpers.dirs.standardize_path(path, sep='-', parents=False)[source]

Standardize file and directory paths.

This function handles camelCase, spaces and special characters while preserving file extensions (".") and operating system path anchors ("/" or "C:\").

Parameters:
  • path (str | pathlib.Path) – The target file or directory path str or pathlib.Path object to clean.

  • sep (str) – The character used to separate words. Defaults to "-".

  • parents (bool) – If True, standardizes all parent directories in the path layout. If False (default), only standardizes the final file or folder name.

Returns:

A standardized operating system path object.

Return type:

pathlib.Path

Examples:

>>> from pyhelpers.dirs import standardize_path
>>> from pathlib import Path

>>> standardize_path('Random Evaluation Name')  # On Windows
WindowsPath('random-evaluation-name')

>>> standardize_path("-license.txt")
WindowsPath('-license.txt')

>>> standardize_path('C:/Users/Username/ProjectData/schema-v2.json')
WindowsPath('C:/Users/Username/ProjectData/schema-v2.json')

>>> standardize_path(Path('/Archive/Old Folders/MyScript.py'), sep="_")
WindowsPath('/Archive/Old Folders/my_script.py')

>>> # Only standardize the filename, leave the directories alone
>>> standardize_path('/Archive/Old Folders/MyScript.py', parents=True)
WindowsPath('/archive/old-folders/my-script.py')