Skip to content

path (8)

expanduser

expanduser(path)

Expand ~ and ~user constructions. If user or $HOME is unknown,

Example

Jinja call:

{{ "~\a" | expanduser }}
Result: ~

DocStrings
Source code in python3.13/posixpath.py
def expanduser(path):
    """Expand ~ and ~user constructions.  If user or $HOME is unknown,
    do nothing."""
    path = os.fspath(path)
    if isinstance(path, bytes):
        tilde = b'~'
    else:
        tilde = '~'
    if not path.startswith(tilde):
        return path
    sep = _get_sep(path)
    i = path.find(sep, 1)
    if i < 0:
        i = len(path)
    if i == 1:
        if 'HOME' not in os.environ:
            try:
                import pwd
            except ImportError:
                # pwd module unavailable, return path unchanged
                return path
            try:
                userhome = pwd.getpwuid(os.getuid()).pw_dir
            except KeyError:
                # bpo-10496: if the current user identifier doesn't exist in the
                # password database, return the path unchanged
                return path
        else:
            userhome = os.environ['HOME']
    else:
        try:
            import pwd
        except ImportError:
            # pwd module unavailable, return path unchanged
            return path
        name = path[1:i]
        if isinstance(name, bytes):
            name = os.fsdecode(name)
        try:
            pwent = pwd.getpwnam(name)
        except KeyError:
            # bpo-10496: if the user name from the path doesn't exist in the
            # password database, return the path unchanged
            return path
        userhome = pwent.pw_dir
    # if no user home, return the path unchanged on VxWorks
    if userhome is None and sys.platform == "vxworks":
        return path
    if isinstance(path, bytes):
        userhome = os.fsencode(userhome)
    userhome = userhome.rstrip(sep)
    return (userhome + path[i:]) or sep

expandvars

expandvars(path)

Expand shell variables of form $var and ${var}. Unknown variables

Example

Jinja call:

{{ "%TEMP%" | expandvars }}
Result: %TEMP%

DocStrings
Source code in python3.13/posixpath.py
def expandvars(path):
    """Expand shell variables of form $var and ${var}.  Unknown variables
    are left unchanged."""
    path = os.fspath(path)
    global _varsub, _varsubb
    if isinstance(path, bytes):
        if b'$' not in path:
            return path
        if not _varsubb:
            import re
            _varsubb = re.compile(_varpattern.encode(), re.ASCII).sub
        sub = _varsubb
        start = b'{'
        end = b'}'
        environ = getattr(os, 'environb', None)
    else:
        if '$' not in path:
            return path
        if not _varsub:
            import re
            _varsub = re.compile(_varpattern, re.ASCII).sub
        sub = _varsub
        start = '{'
        end = '}'
        environ = os.environ

    def repl(m):
        name = m[1]
        if name.startswith(start):
            if not name.endswith(end):
                return m[0]
            name = name[1:-1]
        try:
            if environ is None:
                value = os.fsencode(os.environ[os.fsdecode(name)])
            else:
                value = environ[name]
        except KeyError:
            return m[0]
        else:
            return value

    return sub(repl, path)

fnmatch

fnmatch(name, pat)

Test whether FILENAME matches PATTERN.

Aliases: fnmatch_fnmatch

Example

Jinja call:

{{ "test.txt" | fnmatch("*.txt") }}
Result: True

DocStrings
Source code in python3.13/fnmatch.py
def fnmatch(name, pat):
    """Test whether FILENAME matches PATTERN.

    Patterns are Unix shell style:

    *       matches everything
    ?       matches any single character
    [seq]   matches any character in seq
    [!seq]  matches any char not in seq

    An initial period in FILENAME is not special.
    Both FILENAME and PATTERN are first case-normalized
    if the operating system requires it.
    If you don't want this, use fnmatchcase(FILENAME, PATTERN).
    """
    name = os.path.normcase(name)
    pat = os.path.normcase(pat)
    return fnmatchcase(name, pat)

fnmatch_filter

fnmatch_filter(names, pat)

Construct a list from those elements of the iterable NAMES that match PAT.

Example

Jinja call:

{{ ["test.txt", "test.xyz"] | fnmatch_filter("*.txt") }}
Result: ['test.txt']

DocStrings
Source code in python3.13/fnmatch.py
def filter(names, pat):
    """Construct a list from those elements of the iterable NAMES that match PAT."""
    result = []
    pat = os.path.normcase(pat)
    match = _compile_pattern(pat)
    if os.path is posixpath:
        # normcase on posix is NOP. Optimize it away from the loop.
        for name in names:
            if match(name):
                result.append(name)
    else:
        for name in names:
            if match(os.path.normcase(name)):
                result.append(name)
    return result

fnmatchcase

fnmatchcase(name, pat)

Test whether FILENAME matches PATTERN, including case.

Aliases: fnmatch_fnmatchcase

Example

Jinja call:

{{ "test.txt" | fnmatchcase("*.txt") }}
{{ "test.txt" | fnmatchcase("*.TXT") }}
Result: True False

DocStrings
Source code in python3.13/fnmatch.py
def fnmatchcase(name, pat):
    """Test whether FILENAME matches PATTERN, including case.

    This is a version of fnmatch() which doesn't case-normalize
    its arguments.
    """
    match = _compile_pattern(pat)
    return match(name) is not None

get_directory_tree

get_directory_tree(root_path: 'str | os.PathLike[str]', *, show_hidden: 'bool' = False, show_size: 'bool' = True, show_date: 'bool' = False, show_permissions: 'bool' = False, show_icons: 'bool' = True, max_depth: 'int | None' = None, include_pattern: 'Pattern[str] | None' = None, exclude_pattern: 'Pattern[str] | None' = None, allowed_extensions: 'set[str] | None' = None, hide_empty: 'bool' = True, sort_criteria: 'SortCriteria' = <SortCriteria.NAME: 1>, reverse_sort: 'bool' = False, date_format: 'str' = '%Y-%m-%d %H:%M:%S') -> 'str'

Create a DirectoryTree instance with the specified options.

Example

Jinja call:

{{ "." | get_directory_tree(allowed_extensions=[".py", ".md"]) }}
Result:
📂 ``
┣━━ 📂 `docs`
┃   ┣━━ 📝 `extensions.md`
┃   ┗━━ 📝 `jinjafiles.md`
┣━━ 📂 `overrides`
┣━━ 📂 `src`
┃   ┗━━ 📂 `jinjarope`
┃       ┣━━ 📂 `__pycache__`
┃       ┣━━ 📂 `llm`
┃       ┃   ┣━━ 📂 `__pycache__`
┃       ┃   ┗━━ 🐍 `__init__.py`
┃       ┣━━ 📂 `resources`
┃       ┣━━ 🐍 `__init__.py`
┃       ┣━━ 🐍 `cli.py`
┃       ┣━━ 🐍 `codetree.py`
┃       ┣━━ 🐍 `configloaders.py`
┃       ┣━━ 🐍 `decorators.py`
┃       ┣━━ 🐍 `deepmerge.py`
┃       ┣━━ 🐍 `envconfig.py`
┃       ┣━━ 🐍 `envglobals.py`
┃       ┣━━ 🐍 `environment.py`
┃       ┣━━ 🐍 `envtests.py`
┃       ┣━━ 🐍 `filetree.py`
┃       ┣━━ 🐍 `fsspecloaders.py`
┃       ┣━━ 🐍 `htmlfilters.py`
┃       ┣━━ 🐍 `iconfilters.py`
┃       ┣━━ 🐍 `icons.py`
┃       ┣━━ 🐍 `inspectfilters.py`
┃       ┣━━ 🐍 `iterfilters.py`
┃       ┣━━ 🐍 `jinjafile.py`
┃       ┣━━ 🐍 `jinjaloaderfilesystem.py`
┃       ┣━━ 🐍 `loaderregistry.py`
┃       ┣━━ 🐍 `loaders.py`
┃       ┣━━ 🐍 `localization.py`
┃       ┣━━ 🐍 `manual.py`
┃       ┣━━ 🐍 `mdfilters.py`
┃       ┣━━ 🐍 `regexfilters.py`
┃       ┣━━ 🐍 `rewriteloader.py`
┃       ┣━━ 🐍 `serializefilters.py`
┃       ┣━━ 🐍 `tags.py`
┃       ┣━━ 🐍 `textfilters.py`
┃       ┣━━ 🐍 `undefined.py`
┃       ┗━━ 🐍 `utils.py`
┣━━ 📂 `tests`
┃   ┣━━ 📂 `testresources`
┃   ┣━━ 🐍 `__init__.py`
┃   ┣━━ 🐍 `conftest.py`
┃   ┣━━ 🐍 `test_cli.py`
┃   ┣━━ 🐍 `test_decorators.py`
┃   ┣━━ 🐍 `test_environment.py`
┃   ┣━━ 🐍 `test_fsspec_loaders.py`
┃   ┣━━ 🐍 `test_jinjafile.py`
┃   ┣━━ 🐍 `test_jinjaloaderfilesystem.py`
┃   ┣━━ 🐍 `test_loaders.py`
┃   ┣━━ 🐍 `test_misc_filters.py`
┃   ┣━━ 🐍 `test_nested_dict_loader.py`
┃   ┣━━ 🐍 `test_optional_items.py`
┃   ┣━━ 🐍 `test_rewriteloader.py`
┃   ┣━━ 🐍 `test_tags.py`
┃   ┣━━ 🐍 `test_template_file_loader.py`
┃   ┗━━ 🐍 `test_undefined.py`
┣━━ 📝 `AGENTS.md`
┣━━ 🐍 `duties.py`
┗━━ 📝 `README.md`

DocStrings

Parameters:

Name Type Description Default
root_path str | PathLike[str]

Root path of the directory tree

required
show_hidden bool

Whether to show hidden files/directories

False
show_size bool

Whether to show file sizes

True
show_date bool

Whether to show modification dates

False
show_permissions bool

Whether to show file permissions

False
show_icons bool

Whether to show icons for files/directories

True
max_depth int | None

Maximum depth to traverse (None for unlimited)

None
include_pattern Pattern[str] | None

Regex pattern for files/directories to include

None
exclude_pattern Pattern[str] | None

Regex pattern for files/directories to exclude

None
allowed_extensions set[str] | None

Set of allowed file extensions

None
hide_empty bool

Whether to hide empty directories

True
sort_criteria SortCriteria

Criteria for sorting entries

NAME
reverse_sort bool

Whether to reverse the sort order

False
date_format str

Format string for dates

'%Y-%m-%d %H:%M:%S'

Returns:

Name Type Description
DirectoryTree str

Configured DirectoryTree instance

Source code in src/jinjarope/filetree.py
def get_directory_tree(
    root_path: str | os.PathLike[str],
    *,
    show_hidden: bool = False,
    show_size: bool = True,
    show_date: bool = False,
    show_permissions: bool = False,
    show_icons: bool = True,
    max_depth: int | None = None,
    include_pattern: Pattern[str] | None = None,
    exclude_pattern: Pattern[str] | None = None,
    allowed_extensions: set[str] | None = None,
    hide_empty: bool = True,
    sort_criteria: SortCriteria = SortCriteria.NAME,
    reverse_sort: bool = False,
    date_format: str = "%Y-%m-%d %H:%M:%S",
) -> str:
    """Create a DirectoryTree instance with the specified options.

    Args:
        root_path: Root path of the directory tree
        show_hidden: Whether to show hidden files/directories
        show_size: Whether to show file sizes
        show_date: Whether to show modification dates
        show_permissions: Whether to show file permissions
        show_icons: Whether to show icons for files/directories
        max_depth: Maximum depth to traverse (None for unlimited)
        include_pattern: Regex pattern for files/directories to include
        exclude_pattern: Regex pattern for files/directories to exclude
        allowed_extensions: Set of allowed file extensions
        hide_empty: Whether to hide empty directories
        sort_criteria: Criteria for sorting entries
        reverse_sort: Whether to reverse the sort order
        date_format: Format string for dates

    Returns:
        DirectoryTree: Configured DirectoryTree instance

    Example:
        ```python
        tree = create_directory_tree(
            ".",
            show_hidden=True,
            max_depth=3,
            allowed_extensions={".py", ".txt"},
            exclude_pattern=re.compile(r"__pycache__")
        )
        tree.print_tree()
        ```
    """
    options = TreeOptions(
        show_hidden=show_hidden,
        show_size=show_size,
        show_date=show_date,
        show_permissions=show_permissions,
        show_icons=show_icons,
        max_depth=max_depth,
        include_pattern=include_pattern,
        exclude_pattern=exclude_pattern,
        allowed_extensions=allowed_extensions,
        hide_empty=hide_empty,
        sort_criteria=sort_criteria,
        reverse_sort=reverse_sort,
        date_format=date_format,
    )

    return DirectoryTree(root_path, options).get_tree_text()

glob

glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)

Return a list of paths matching a pathname pattern.

Example

Jinja call:

{{ ".*" | glob }}
Result: ['.git', '.gitignore', '.venv', '.github', '.pre-commit-config.yaml']

DocStrings
Source code in python3.13/glob.py
def glob(pathname, *, root_dir=None, dir_fd=None, recursive=False,
        include_hidden=False):
    """Return a list of paths matching a `pathname` pattern.

    The pattern may contain simple shell-style wildcards a la
    fnmatch. Unlike fnmatch, filenames starting with a
    dot are special cases that are not matched by '*' and '?'
    patterns by default.

    The order of the returned list is undefined. Sort it if you need a
    particular order.

    If `root_dir` is not None, it should be a path-like object specifying
    the root directory for searching.  It has the same effect as changing
    the current directory before calling it (without actually changing it).
    If pathname is relative, the result will contain paths relative to
    `root_dir`.

    If `dir_fd` is not None, it should be a file descriptor referring to a
    directory, and paths will then be relative to that directory.

    If `include_hidden` is true, wildcards can match path segments beginning
    with a dot ('.').

    If `recursive` is true, the pattern '**' will match any files and
    zero or more directories and subdirectories.
    """
    return list(iglob(pathname, root_dir=root_dir, dir_fd=dir_fd, recursive=recursive,
                      include_hidden=include_hidden))

path_join

path_join(a, *p)

Join two or more pathname components, inserting '/' as needed.

Example

Jinja call:

{{ "a" | path_join("b") }}
Result: a/b

DocStrings
Source code in python3.13/posixpath.py
def join(a, *p):
    """Join two or more pathname components, inserting '/' as needed.
    If any component is an absolute path, all previous path components
    will be discarded.  An empty last part will result in a path that
    ends with a separator."""
    a = os.fspath(a)
    sep = _get_sep(a)
    path = a
    try:
        for b in p:
            b = os.fspath(b)
            if b.startswith(sep) or not path:
                path = b
            elif path.endswith(sep):
                path += b
            else:
                path += sep + b
    except (TypeError, AttributeError, BytesWarning):
        genericpath._check_arg_types('join', a, *p)
        raise
    return path