Skip to content

Commit ecb159f

Browse files
redjaxredjax
and
redjax
authored
Add list_files() function to file_utils (#261)
Co-authored-by: redjax <[email protected]>
1 parent d6e3531 commit ecb159f

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

red_utils/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
benchmark,
1212
)
1313
from .dict_utils import debug_dict, merge_dicts, update_dict, validate_dict
14-
from .file_utils import crawl_dir, default_json_dir, export_json, ts
14+
from .file_utils import crawl_dir, default_json_dir, export_json, ts, list_files
1515
from .hash_utils import get_hash_from_str
1616
from .time_utils import (
1717
datetime_as_dt,

red_utils/file_utils/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
from __future__ import annotations
22

33
from .constants import default_json_dir, ts
4-
from .operations import crawl_dir, export_json
4+
from .operations import crawl_dir, export_json, list_files

red_utils/file_utils/operations.py

+32
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
from .constants import default_json_dir, ts
1111

12+
1213
def export_json(
1314
input: Union[str, list[list, dict], dict[str, Any]] = None,
1415
output_dir: str = default_json_dir,
@@ -132,3 +133,34 @@ def crawl_dir(
132133
return_obj: dict[str, list[Path]] = {"files": files, "dirs": dirs}
133134

134135
return return_obj
136+
137+
138+
def list_files(in_dir: str = None, ext_filter: str = None) -> list[Path]:
139+
"""Return list of all files in a path, optionally filtering by file extension."""
140+
if not in_dir:
141+
raise ValueError("Missing input directory to search")
142+
if ext_filter is not None:
143+
if not ext_filter.startswith("."):
144+
ext_filter = f".{ext_filter}"
145+
146+
if ext_filter:
147+
search_str: str = f"**/{ext_filter}"
148+
else:
149+
search_str: str = "**/*"
150+
151+
return_files: list[Path] = []
152+
153+
try:
154+
for _p in Path(in_dir).glob(search_str):
155+
if _p.is_file():
156+
return_files.append(_p)
157+
except FileNotFoundError as fnf:
158+
raise FileNotFoundError(f"Could not find input path: {in_dir}. Details: {fnf}")
159+
except PermissionError as perm:
160+
raise PermissionError(f"Could not open path: {in_dir}. Details: {perm}")
161+
except Exception as exc:
162+
raise Exception(
163+
f"Unhandled exception looping input path: {in_dir}. Details: {exc}"
164+
)
165+
166+
return return_files

0 commit comments

Comments
 (0)