resolve_dir_path

pyhelpers.dirs.resolve_dir_path(dir_path=None, subdir='', msg='Invalid input!', **kwargs)[source]

Resolve a directory path into an absolute pathname.

This function accepts a variety of input types and converts them into a standardized directory pathname via cd(). If dir_path is not given, subdir is used instead (or the current directory, if subdir is also not given).

Note

Both a relative and an absolute dir_path are routed through the same call to cd(), on the assumption that cd (like os.path.join) treats an absolute argument as replacing any preceding base directory, so **kwargs (e.g. mkdir=True) is applied consistently either way. If cd does not behave this way for absolute paths, this needs revisiting.

Parameters:
  • dir_path (str | bytes | os.PathLike | None) – Pathname of a data directory; if dir_path=None (default), subdir is examined instead to construct a valid directory path.

  • subdir (str | bytes | os.PathLike) – Name of a subdirectory to fall back on when dir_path=None. Defaults to "".

  • msg (str) – Error message used when dir_path cannot be decoded into a valid pathname. Defaults to "Invalid input!".

  • kwargs – [Optional] Additional parameters for cd() (e.g. mkdir=True to create the directory if it does not already exist).

Returns:

Valid pathname of a directory.

Return type:

pathlib.Path

Examples:

>>> from pyhelpers.dirs import resolve_dir_path, get_relative_path
>>> from pathlib import Path

>>> data_dir = resolve_dir_path()
>>> get_relative_path(data_dir)
'.'

>>> data_dir = resolve_dir_path("tests")
>>> get_relative_path(data_dir)
'tests'

>>> data_dir = resolve_dir_path(subdir=Path("data"))
>>> get_relative_path(data_dir)
'data'