| from __future__ import annotations |
|
|
| import csv |
| import json |
| from pathlib import Path |
| from typing import Iterable |
|
|
|
|
| def ensure_parent(path: Path) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
|
|
|
|
| def write_json(path: Path, data: object) -> None: |
| ensure_parent(path) |
| with path.open("w", encoding="utf-8") as handle: |
| json.dump(data, handle, ensure_ascii=False, indent=2, sort_keys=True) |
| handle.write("\n") |
|
|
|
|
| def write_jsonl(path: Path, rows: Iterable[dict]) -> int: |
| ensure_parent(path) |
| count = 0 |
| with path.open("w", encoding="utf-8") as handle: |
| for row in rows: |
| handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True)) |
| handle.write("\n") |
| count += 1 |
| return count |
|
|
|
|
| def read_jsonl(path: Path) -> list[dict]: |
| rows: list[dict] = [] |
| with path.open(encoding="utf-8") as handle: |
| for line in handle: |
| line = line.strip() |
| if line: |
| rows.append(json.loads(line)) |
| return rows |
|
|
|
|
| def write_csv(path: Path, rows: Iterable[dict], fieldnames: list[str] | None = None) -> int: |
| row_list = list(rows) |
| if fieldnames is None: |
| fieldnames = [] |
| seen = set() |
| for row in row_list: |
| for key in row: |
| if key not in seen: |
| fieldnames.append(key) |
| seen.add(key) |
| ensure_parent(path) |
| with path.open("w", newline="", encoding="utf-8") as handle: |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) |
| writer.writeheader() |
| for row in row_list: |
| writer.writerow({key: row.get(key, "") for key in fieldnames}) |
| return len(row_list) |
|
|
|
|
| def read_csv_dicts(path: Path) -> list[dict[str, str]]: |
| with path.open(newline="", encoding="utf-8") as handle: |
| return list(csv.DictReader(handle)) |
|
|