mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-10-24 18:27:01 +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
|
import csv
|
||||||
|
from collections.abc import Mapping
|
||||||
from typing import Any, Sequence, TextIO, Type, Union
|
from typing import Any, Sequence, TextIO, Type, Union
|
||||||
|
|
||||||
CsvDialect = Union[str, csv.Dialect, Type[csv.Dialect]]
|
CsvDialect = Union[str, csv.Dialect, Type[csv.Dialect]]
|
||||||
|
|
@ -24,7 +25,16 @@ def rows_to_csv_file(
|
||||||
if description is None:
|
if description is None:
|
||||||
raise ValueError("Cursor does not have result columns")
|
raise ValueError("Cursor does not have result columns")
|
||||||
|
|
||||||
|
columns = [column[0] for column in description]
|
||||||
writer = csv.writer(file, dialect=dialect, **writer_kwargs)
|
writer = csv.writer(file, dialect=dialect, **writer_kwargs)
|
||||||
if header:
|
if header:
|
||||||
writer.writerow([column[0] for column in description])
|
writer.writerow(columns)
|
||||||
writer.writerows(cursor)
|
|
||||||
|
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