normalize_path

pyhelpers.dirs.normalize_path(path, sep='/', as_str=True, prepend_dot=False)[source]

Convert a path into a consistent format for cross-platform compatibility.

This function converts all path separators ("\" and "/") into a single, consistent separator and collapses consecutive separators, so that the resulting path is consistent across systems (e.g. Windows and Unix-like operating systems).

Note

A run of leading separators (e.g. a Windows UNC prefix such as "\\server\share") is also collapsed to a single separator. This function does not preserve UNC-style double-slash prefixes; avoid it for network-share paths.

Parameters:
  • path (str | bytes | pathlib.Path | os.PathLike) – The filesystem path to normalize.

  • sep (str) – Path separator used when the result is returned as a string; this is ignored when as_str=False, in which case the separator is determined automatically by pathlib.Path based on the current platform. Defaults to "/".

  • as_str (bool) – Whether to return the normalized path as a string; if False, a pathlib.Path object is returned instead. Defaults to True.

  • prepend_dot (bool) – If True, prepends "./" to a relative path that does not already begin with "./", "../", or a path that pathlib considers absolute on the current platform. Note that on Windows, a path with a leading separator but no drive letter (e.g. "/pyhelpers/data") is drive-relative, not absolute, and will have "./" prepended; on POSIX systems, that same path is absolute and is left untouched. Only takes effect when as_str=True, since pathlib.Path normalizes away a leading "./" when constructing a Path object. Defaults to False.

Returns:

Pathname formatted to a consistent standard, either as a string (default) or as a pathlib.Path object when as_str=False.

Return type:

str | pathlib.Path

Examples:

>>> from pyhelpers.dirs import normalize_path
>>> from pathlib import Path
>>> import os

>>> path = "tests\data\dat.csv"
>>> normalize_path(path)
'tests/data/dat.csv'

>>> normalize_path(path, prepend_dot=True)
'./tests/data/dat.csv'

>>> path = "tests//data/dat.csv"
>>> normalize_path(path)
'tests/data/dat.csv'

>>> path = Path("tests\data/dat.csv")  # Assuming Windows OS
>>> normalize_path(path, sep=os.sep)
'tests\data\dat.csv'
>>> normalize_path(path, sep=os.sep, as_str=False)
WindowsPath('tests/data/dat.csv')

>>> # on POSIX: absolute, untouched
>>> normalize_path("/usr/bin", prepend_dot=True)
'/usr/bin'
>>> # on Windows: drive-relative, not absolute
>>> normalize_path("/usr/bin", prepend_dot=True)
'./usr/bin'