comparison sqlex/model.py @ 9:834b920ae345 default tip

allow output of headers in csv
author Jeff Hammel <k0scist@gmail.com>
date Sat, 01 Apr 2017 15:11:34 -0700
parents 22fbe50d92e8
children
comparison
equal deleted inserted replaced
8:adf056d67c01 9:834b920ae345
65 TYPE_INDEX = 2 65 TYPE_INDEX = 2
66 return OrderedDict([(row[NAME_INDEX], row[TYPE_INDEX]) 66 return OrderedDict([(row[NAME_INDEX], row[TYPE_INDEX])
67 for row in data]) 67 for row in data])
68 68
69 69
70 def table2csv(self, table, fp): 70 def table2csv(self, table, fp, header=False):
71 """ 71 """
72 export `table` to `fp` file object in CSV format 72 export `table` to `fp` file object in CSV format
73 """ 73 """
74 # TODO: option to add column headers 74 # TODO: option to add column headers
75 75
78 78
79 # get whole table 79 # get whole table
80 sql = 'select * from {table}'.format(table=table) 80 sql = 'select * from {table}'.format(table=table)
81 rows = self(sql) 81 rows = self(sql)
82 82
83 if header:
84 # export header as first row, if specified
85 _header = self.columns(table).keys()
86 if _header:
87 _header[0] = '#{}'.format(_header[0])
88 rows.insert(0, _header)
89
83 # decode unicde because the CSV module won't 90 # decode unicde because the CSV module won't
84 # http://stackoverflow.com/questions/22733642/how-to-write-a-unicode-csv-in-python-2-7 91 # http://stackoverflow.com/questions/22733642/how-to-write-a-unicode-csv-in-python-2-7
85 rows = [[unicode(s).encode("utf-8") for s in row] 92 rows = [[unicode(s).encode("utf-8") for s in row]
86 for row in rows] 93 for row in rows]
87 94