Coverage for app / util / file.py: 38%
24 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1import os
2from pydantic import BaseModel
3import json
6def dir_exists(path):
7 """Check if a directory exists."""
8 return os.path.isdir(path)
11def dir_files(path, suffix: str | None = None, rmsuffix: bool = True):
12 """Return files in dir"""
13 files: list[str] = [f for f in os.listdir(path) if os.path.isfile(f"{path}/{f}")]
14 if suffix is not None:
15 files = [
16 f.removesuffix(suffix) if rmsuffix else f
17 for f in files
18 if f.endswith(suffix)
19 ]
20 return files
23def file_exists(path):
24 """Check if a file exists."""
25 return os.path.isfile(path)
28def write_file(path, data):
29 """Write data to a file (overwrites if exists)."""
30 with open(path, "w", encoding="utf-8") as f:
31 f.write(data)
34def read_file(path):
35 """Read and return contents of a file."""
36 with open(path, "r", encoding="utf-8") as f:
37 return f.read()
40def read_json_file_as_model(path, model: type[BaseModel]) -> BaseModel:
41 """Read a JSON file and parse it into a Pydantic model."""
42 with open(path, "r", encoding="utf-8") as f:
43 data = json.load(f)
44 if isinstance(data, list):
45 return [model(**d) for d in data]
46 return model(**data)