Download src/utils/file_io.py from danishk84/NovaGuide: direct link, hf CLI and curl.
- Browser
- Download file 1.6 kB
-
https://huggingface.co/spaces/danishk84/NovaGuide/resolve/main/src/utils/file_io.py
- Command line
-
hf download hf://spaces/danishk84/NovaGuide/src/utils/file_io.py
-
curl -L -o file_io.py https://huggingface.co/spaces/danishk84/NovaGuide/resolve/main/src/utils/file_io.py
1.6 kB
| """UTF-8 file-loading helpers for NovaGuide datasets.""" | |
| from __future__ import annotations | |
| import csv | |
| import json | |
| from pathlib import Path | |
| from typing import Any | |
| def _existing_file(path: str) -> Path: | |
| """Resolve a file path and raise a clear error when it does not exist.""" | |
| file_path = Path(path) | |
| if not file_path.is_file(): | |
| raise FileNotFoundError(f"NovaGuide data file not found: {file_path}") | |
| return file_path | |
| def load_json(path: str) -> Any: | |
| """Load and return a UTF-8 JSON document.""" | |
| with _existing_file(path).open("r", encoding="utf-8") as handle: | |
| return json.load(handle) | |
| def load_jsonl(path: str) -> list[dict[str, Any]]: | |
| """Load non-blank JSONL lines as dictionaries.""" | |
| records: list[dict[str, Any]] = [] | |
| with _existing_file(path).open("r", encoding="utf-8") as handle: | |
| for line_number, line in enumerate(handle, start=1): | |
| if not line.strip(): | |
| continue | |
| value = json.loads(line) | |
| if not isinstance(value, dict): | |
| raise ValueError(f"JSONL line {line_number} is not an object: {path}") | |
| records.append(value) | |
| return records | |
| def load_csv_records(path: str) -> list[dict[str, str]]: | |
| """Load a UTF-8 CSV file as a list of row dictionaries.""" | |
| with _existing_file(path).open("r", encoding="utf-8-sig", newline="") as handle: | |
| return list(csv.DictReader(handle)) | |
| def ensure_dir(path: str) -> None: | |
| """Create a directory and its parents when they do not exist.""" | |
| Path(path).mkdir(parents=True, exist_ok=True) | |