cd

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

Specifies the pathname of a directory (or file).

Parameters:
  • subdir (str | os.PathLike | bytes) – Name of a directory or directories (and/or a filename).

  • mkdir (bool) – Whether to create the directory; defaults to False.

  • cwd (str | os.PathLike | bytes | | None) – Current working directory; defaults to None.

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

  • kwargs – [Optional] Additional parameters (e.g. mode=0o777) for the function os.makedirs.

Returns:

Pathname of the directory or file.

Return type:

str

Examples:

>>> from pyhelpers.dirs import cd
>>> import os
>>> import pathlib
>>> current_wd = cd()  # Current working directory
>>> os.path.relpath(current_wd)
'.'
>>> # The directory will be created if it does not exist
>>> path_to_tests_dir = cd("tests")
>>> os.path.relpath(path_to_tests_dir)
'tests'
>>> path_to_tests_dir = cd(pathlib.Path("tests"))
>>> os.path.relpath(path_to_tests_dir)
'tests'
>>> path_to_tests_dir = cd("tests\folder1/folder2")
>>> os.path.relpath(path_to_tests_dir)
'tests\folder1\folder2'