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 bypathlib.Pathbased on the current platform. Defaults to"/".as_str (bool) – Whether to return the normalized path as a string; if
False, apathlib.Pathobject is returned instead. Defaults toTrue.prepend_dot (bool) – If
True, prepends"./"to a relative path that does not already begin with"./","../", or a path thatpathlibconsiders 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 whenas_str=True, sincepathlib.Pathnormalizes away a leading"./"when constructing aPathobject. Defaults toFalse.
- Returns:
Pathname formatted to a consistent standard, either as a string (default) or as a
pathlib.Pathobject whenas_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'