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 path resides 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, a pathlib.Path object is returned instead and normalized, quoted, is_dir and prepend_dot are all ignored. Defaults to False.

  • normalized (bool) – Whether to run the path through _normalize_path() (or, when quoted=True, _format_display_path()) before returning it as a string. If False, the string is returned using the native OS separator, unnormalized. Only takes effect when as_str=True. Defaults to True.

  • 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 when as_str=True. Defaults to False.

  • is_dir (bool | None) – Explicitly treat the path as a directory; passed through to _format_display_path(). Only takes effect when as_str=True and quoted=True. Defaults to None.

  • prepend_dot (bool) – Whether to prepend a dot-relative prefix to a relative path. Only takes effect when as_str=True. Defaults to False.

Returns:

A location relative to the current working directory if path is within the working space; otherwise, a resolved copy of the absolute path.

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'