SXXXXXXX_PyUCC/pyucc/utils/csv_exporter.py

28 lines
752 B
Python

from typing import Iterable, Sequence
import csv
from pathlib import Path
def export_rows_to_csv(
path: str | Path, headers: Sequence[str], rows: Iterable[Sequence]
) -> int:
"""Export rows to a CSV file.
Args:
path: destination file path (string or Path)
headers: list/sequence of header strings
rows: iterable of row sequences (each row is a sequence of values)
Returns:
int: number of rows written (excluding header)
"""
p = Path(path)
written = 0
with p.open("w", newline="", encoding="utf-8") as fh:
writer = csv.writer(fh)
writer.writerow(list(headers))
for row in rows:
writer.writerow(list(row))
written += 1
return written