| 1 |
""" |
| 2 |
Wrinting data in CSV. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import codecs |
| 12 |
import csv |
| 13 |
|
| 14 |
from gavo import base |
| 15 |
from gavo import rsc |
| 16 |
from gavo.formats import common |
| 17 |
|
| 18 |
|
| 19 |
def _defuseString(val): |
| 20 |
# a cheaty way of making sure we get hex escapes for non-printable stuff |
| 21 |
if isinstance(val, str): |
| 22 |
return repr(val)[1:-1] |
| 23 |
return val |
| 24 |
|
| 25 |
|
| 26 |
def _defuseRow(row): |
| 27 |
"""returns row, where strings with non-printables have them replaced |
| 28 |
with backslash escapes. |
| 29 |
""" |
| 30 |
return [_defuseString(v) for v in row] |
| 31 |
|
| 32 |
|
| 33 |
def writeDataAsCSV(table, target, acquireSamples=True, |
| 34 |
dialect=base.getConfig("async", "csvDialect"), headered=False): |
| 35 |
"""writes table to the file target in CSV. |
| 36 |
|
| 37 |
The CSV format chosen is controlled through the async/csvDialect |
| 38 |
config item. |
| 39 |
|
| 40 |
If headered is True, we also include table params (if present) |
| 41 |
in comments. |
| 42 |
""" |
| 43 |
if isinstance(table, rsc.Data): |
| 44 |
table = table.getPrimaryTable() |
| 45 |
sm = base.SerManager(table, acquireSamples=acquireSamples) |
| 46 |
|
| 47 |
# our targets are always binary files; csv can't deal with that. |
| 48 |
target = codecs.getwriter("utf-8")(target) |
| 49 |
writer = csv.writer(target, dialect) |
| 50 |
|
| 51 |
if headered: |
| 52 |
for param in table.iterParams(): |
| 53 |
if param.value is not None: |
| 54 |
target.write(("# %s = %s // %s\r\n"%( |
| 55 |
param.name, |
| 56 |
param.getStringValue(), |
| 57 |
param.description))) |
| 58 |
|
| 59 |
writer.writerow([c["name"] for c in sm]) |
| 60 |
|
| 61 |
for row in sm.getMappedTuples(): |
| 62 |
writer.writerow(_defuseRow(row)) |
| 63 |
|
| 64 |
|
| 65 |
# NOTE: This will only serialize the primary table |
| 66 |
common.registerDataWriter("csv_bare", writeDataAsCSV, "text/csv", |
| 67 |
"CSV without column labels", ".csv") |
| 68 |
common.registerDataWriter("csv", |
| 69 |
lambda table, target, **kwargs: |
| 70 |
writeDataAsCSV(table, target, headered=True, **kwargs), |
| 71 |
"text/csv;header=present", |
| 72 |
"CSV with column labels", ".csv") |