Source code for sdt.io.fs

# SPDX-FileCopyrightText: 2020 Lukas Schrangl <lukas.schrangl@tuwien.ac.at>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Some functions related to files and the file system"""

import contextlib
import os
import re
from pathlib import Path
from typing import Literal, overload


[docs] @contextlib.contextmanager def chdir(path): """Context manager to temporarily change the working directory Parameters ---------- path : str Path of the directory to change to. :py:func:`os.path.expanduser` is called on this. Examples -------- >>> with chdir("subdir"): ... # here the working directory is "subdir" >>> # here we are back """ old_wd = os.getcwd() os.chdir(os.path.expanduser(str(path))) try: yield finally: os.chdir(old_wd)
@overload def get_files( pattern: str, subdir: str | Path = ..., id_dict: Literal[False] = ..., parse_numbers: bool = ..., ) -> tuple[list[str], list[tuple]]: ... @overload def get_files( pattern: str, subdir: str | Path = ..., id_dict: Literal[True] = ..., parse_numbers: bool = ..., ) -> tuple[list[str], list[dict]]: ...
[docs] def get_files(pattern, subdir=Path(), id_dict=False, parse_numbers=True): r"""Get all files matching a regular expression Parameters ---------- pattern Regular expression to search in the file name. Search is performed on the path relative to `subdir`. One can also define groups (using parenthesis), which will be returned in addition to the matching file names. **A note to Windows users: Use a forward slash (/) for subdirectories.** subdir Any regular expression matching will be performed relative to `subdir`. id_dict If `True`, return IDs as a dict. Only works for named groups in `pattern`. parse_numbers If `True`, try to convert regular expression matches to int and float. Returns ------- : sorted list of file where `pattern` could be matched : values of the groups defined in the `pattern`. If `id_dict` is `True`, this is a `dict` mapping named groups to their values. Otherwise, this is a list of group value tuples. If `parse_numbers` is `True`, try to convert group values to int/float. Examples -------- >>> names, ids = get_files(r"^image_(.*)_(\d{3}).tif$", "subdir") >>> names ['image_xxx_001.tif', 'image_xxx_002.tif', 'image_yyy_003.tif'] >>> ids [('xxx', 1), ('xxx', 2), ('yyy', 3)] """ if parse_numbers: def _conv_value(v: str) -> int | float | str: for conv in int, float: try: # try conversion to int and float ret = conv(v) break except ValueError: pass else: # keep str if all conversions failed ret = v return ret else: def _conv_value(v: str) -> str: return v r = re.compile(pattern) flist = [] idlist = [] for dp, _, fn in os.walk(subdir): reldir = Path(dp).relative_to(subdir) for f in fn: relp = (reldir / f).as_posix() m = r.search(relp) if m is None: continue # For compatibility, append path as string. # However, one could simply append reldir / f flist.append(relp) if id_dict: ids = {k: _conv_value(v) for k, v in m.groupdict().items()} else: ids = tuple(_conv_value(v) for v in m.groups()) idlist.append(ids) slist = sorted(zip(flist, idlist), key=lambda x: x[0]) return [s[0] for s in slist], [s[1] for s in slist]