cd

pyhelpers.dirs.cd(*subdir, mkdir=False, cwd=None, back_check=False, as_str=False, normalized=True, **kwargs)[source]

Specify and resolve the pathname of a directory or file.

This function constructs an operating system-agnostic path object. Handles missing directories and resolves parent path traversal dynamically.

Parameters:
  • subdir (str | bytes | pathlib.Path | os.PathLike | None) – Name of a directory or directories (and/or a filename). None values are safely ignored.

  • mkdir (bool) – Whether to create the directory if it does not exist. Defaults to False.

  • cwd (str | bytes | pathlib.Path | os.PathLike | None) – Current working directory fallback. Defaults to None.

  • back_check (bool) – Whether to check if a parent directory exists. Defaults to False.

  • as_str (bool) – If True, forces the return type to be a standard string instead of a path object. Defaults to False.

  • normalized (bool) – Whether to normalize the returned pathname structurally. Defaults to True.

  • kwargs – Optional parameters (e.g. mode=0o777) passed to pathlib.Path.mkdir.

Returns:

A standardized path object representing the target directory or file.

Return type:

Path | str

Examples:

>>> from pyhelpers.dirs import cd
>>> from pathlib import Path

>>> cur_dir = cd()  # Current working directory
>>> cur_dir.name
'pyhelpers'

>>> cd(None).relative_to(cur_dir)  # On Windows OS
WindowsPath('.')

>>> # The directory will be created if it does not exist
>>> test_path = cd("tests")
>>> test_path.relative_to(cur_dir)
WindowsPath('tests')

>>> test_path = cd("tests\folder1/folder2")
>>> test_path.relative_to(cur_dir)
WindowsPath('tests/folder1/folder2')

>>> test_path = cd(Path("tests\folder1"), as_str=True, normalized=False)
>>> test_path  # On Windows OS
'X:\pyhelpers\tests\folder1'