mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-10-23 17:57:03 +02:00
Handle mapping rows in CSV export helper
This commit is contained in:
parent
fb53549500
commit
8af34609f3
1 changed files with 12 additions and 2 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import csv
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Sequence, TextIO, Type, Union
|
||||
|
||||
CsvDialect = Union[str, csv.Dialect, Type[csv.Dialect]]
|
||||
|
|
@ -24,7 +25,16 @@ def rows_to_csv_file(
|
|||
if description is None:
|
||||
raise ValueError("Cursor does not have result columns")
|
||||
|
||||
columns = [column[0] for column in description]
|
||||
writer = csv.writer(file, dialect=dialect, **writer_kwargs)
|
||||
if header:
|
||||
writer.writerow([column[0] for column in description])
|
||||
writer.writerows(cursor)
|
||||
writer.writerow(columns)
|
||||
|
||||
def rows():
|
||||
for row in cursor:
|
||||
if isinstance(row, Mapping):
|
||||
yield [row[column] for column in columns]
|
||||
else:
|
||||
yield row
|
||||
|
||||
writer.writerows(rows())
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue