normalize_pathname¶
- pyhelpers.dirs.normalize_pathname(pathname, sep='/', add_slash=False, **kwargs)[source]¶
Converts a pathname to a consistent file path format for cross-platform compatibility.
This function formats a file (or an OS-specific) path to ensure compatibility across Windows and Ubuntu (and other Unix-like systems).
- Parameters:
pathname (str | bytes | pathlib.Path | os.PathLike) – A pathname.
sep (str) – File path separator used by the operating system; defaults to
"/"
(forward slash) for both Windows and Ubuntu (and other Unix-like systems).add_slash (bool) – If
True
, adds a leading slash (and, if appropriate, a trailing slash) to the returned pathname; defaults toFalse
.
- Returns:
Pathname of a consistent file path format.
- Return type:
str
Examples:
>>> from pyhelpers.dirs import normalize_pathname >>> import os >>> import pathlib >>> normalize_pathname("tests\data\dat.csv") 'tests/data/dat.csv' >>> normalize_pathname("tests\data\dat.csv", add_slash=True) # on Windows './tests/data/dat.csv' >>> normalize_pathname("tests//data/dat.csv") 'tests/data/dat.csv' >>> pathname = pathlib.Path("tests\data/dat.csv") >>> normalize_pathname(pathname, sep=os.path.sep) # On Windows 'tests\data\dat.csv' >>> normalize_pathname(pathname, sep=os.path.sep, add_slash=True) # On Windows '.\tests\data\dat.csv'