| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| from typing import Any | |
| import pandas as pd | |
| def read_table(path: str | Path) -> pd.DataFrame: | |
| """Read a CSV, JSONL, JSON, or Parquet table.""" | |
| path = Path(path) | |
| suffix = path.suffix.lower() | |
| if suffix == ".parquet": | |
| return pd.read_parquet(path) | |
| if suffix == ".csv": | |
| return pd.read_csv(path) | |
| if suffix == ".jsonl": | |
| return pd.read_json(path, lines=True) | |
| if suffix == ".json": | |
| return pd.read_json(path) | |
| raise ValueError(f"Unsupported table format: {path}") | |
| def write_json(obj: dict[str, Any], path: str | Path) -> None: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(obj, indent=2, sort_keys=True) + "\n", encoding="utf-8") | |
| def write_csv(df: pd.DataFrame, path: str | Path) -> None: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| df.to_csv(path, index=False) | |