| 391 | |
| 392 | |
| 393 | def _to_csv( |
| 394 | box_list, filename: str | PathLike | None = None, encoding: str = "utf-8", errors: str = "strict", **kwargs |
| 395 | ): |
| 396 | csv_column_names = list(box_list[0].keys()) |
| 397 | for row in box_list: |
| 398 | if list(row.keys()) != csv_column_names: |
| 399 | raise BoxError("BoxList must contain the same dictionary structure for every item to convert to csv") |
| 400 | |
| 401 | out_data: IO[str] |
| 402 | if filename: |
| 403 | _exists(filename, create=True) |
| 404 | out_data = open(filename, "w", encoding=encoding, errors=errors, newline="") |
| 405 | else: |
| 406 | out_data = StringIO("") |
| 407 | writer = csv.DictWriter(out_data, fieldnames=csv_column_names, **kwargs) |
| 408 | writer.writeheader() |
| 409 | for data in box_list: |
| 410 | writer.writerow(data) |
| 411 | if not filename: |
| 412 | return out_data.getvalue() # type: ignore |
| 413 | out_data.close() |
| 414 | |
| 415 | |
| 416 | def _from_csv( |