therepy.here
Module Contents
Classes
Simplify file path management for project-oriented python workflows. |
- class therepy.here.Here(pattern, skip=0, as_str=False)
Simplify file path management for project-oriented python workflows. Create an instance of Here and specify the project’s root directory. Use Here.here(“relative/path/from/root”) to get the absolute path to a file or folder inside your root directory. Here returns instances of pathlib.Path by default, but can be set to return strings instead.
- Parameters:
pattern (str) – Either the exact name of the root directory for your project or a glob- style expression which identifies a file or folder within your root directory.
skip (int, default=0) – The number of occurrences of ‘pattern’ to skip as the current working path is travsersed backwards.
as_str (bool, default=False) – Sets the default return type for Here.here. If False (the default), Here.here returns a pathlib.Path. If True, it just returs a string. This can be overwritten by specifying ‘as_str’ in the Here.here call.
Examples
>>> from therepy import Here >>> here = Here("my_project") >>> here.here("folder/dataset.csv") PosixPath("/home/user/Documents/my_project/folder/dataset.csv")
You can also declare the root directory by providing the name of a file or folder inside of your project’s root.
>>> here = Here(".git")
Glob style expressions also work for identifying files.
>>> here = Here("*.Rproj")
By default, Here.here returns a pathlib.Path. That behavior can be overwritten at initialization or in downstream methods.
>>> here = Here("my_project", as_str=True) >>> here.here() "/home/user/Documents/my_project" >>> here.here("my_project", as_str=False) PosixPath("/home/user/Documents/my_project")
If your pattern occurs multiple times in your working path, you can skip to the desired occurrence.
>>> from pathlib import Path >>> Path.cwd() PosixPath("/home/user/Documents/module/module") >>> here = Here("module", skip=0) >>> here.here() PosixPath("/home/user/Documents/module/module") >>> here = Here("module", skip=1) >>> here.here() PosixPath("/home/user/Documents/module")
- here(*path, as_str=None)
Get the absolute path to a file/folder within the project directory.
- Parameters:
*path (str or tuple of str) – The relative path from the project root directory to the target file or folder. Can be concatenated as one string, or each folder/file can be listed separately. If not provided, the absolute path to the root directory will be returned. If an absolute path is provided instead of a relative path, it will be resolved and the correct path will be returned.
as_str (bool or None, default=None) – If True, return a string. If False, return a pathlib.Path. If None, (the default) Here.here uses the value for ‘as_str’ set at initialization, which itself defaults to False.
- Returns:
The absolute path to the provided relative path.
- Return type:
pathlib.Path or str