get_relative_path¶
- pyhelpers.dirs.get_relative_path(path, as_str=False, normalized=True, quoted=False, is_dir=None, prepend_dot=False)[source]¶
Check if the pathname is relative to the current working directory.
If the specified
pathresides within the current working directory, this function returns its relative path counterpart. Otherwise, it returns the original absolute path.- Parameters:
path (str | bytes | pathlib.Path | os.PathLike) – Pathname of a file or directory.
as_str (bool) – Whether to return the path as a string; if
False, apathlib.Pathobject is returned instead andnormalized,quoted,is_dirandprepend_dotare all ignored. Defaults toFalse.normalized (bool) – Whether to run the path through
_normalize_path()(or, whenquoted=True,_format_display_path()) before returning it as a string. IfFalse, the string is returned using the native OS separator, unnormalized. Only takes effect whenas_str=True. Defaults toTrue.quoted (bool) – Whether to format and wrap the returned string via
_format_display_path()(double-quoted, with a trailing separator for directories) instead of_normalize_path(). Only takes effect whenas_str=True. Defaults toFalse.is_dir (bool | None) – Explicitly treat the path as a directory; passed through to
_format_display_path(). Only takes effect whenas_str=Trueandquoted=True. Defaults toNone.prepend_dot (bool) – Whether to prepend a dot-relative prefix to a relative path. Only takes effect when
as_str=True. Defaults toFalse.
- Returns:
A location relative to the current working directory if
pathis within the working space; otherwise, a resolved copy of the absolutepath.- Return type:
pathlib.Path | str
Examples:
>>> from pyhelpers.dirs import get_relative_path, cd >>> get_relative_path(path=".") # on Windows WindowsPath('.') >>> get_relative_path(path=cd(), as_str=True) '.' >>> get_relative_path(path="C:/Windows", as_str=True) 'C:/Windows' >>> get_relative_path(path="C:\Program Files", as_str=True, normalized=False) 'C:\Program Files'