Revision 14592
Added by Aaron Marcuse-Kubitza over 10 years ago
trunk/lib/csvs.py | ||
---|---|---|
5 | 5 |
import StringIO |
6 | 6 |
|
7 | 7 |
import exc |
8 |
import lists |
|
8 | 9 |
import streams |
9 | 10 |
import strings |
10 | 11 |
import util |
... | ... | |
197 | 198 |
'''Adds column(s) to each row |
198 | 199 |
@param mk_value(row, row_num) | literal_value |
199 | 200 |
''' |
200 |
def __init__(self, reader, mk_value, index=0, n=1): |
|
201 |
def __init__(self, reader, mk_value, index=0, n=1, col_names=None): |
|
202 |
line_num_skip = 0 |
|
203 |
if col_names != None: |
|
204 |
col_names = lists.mk_seq(col_names) |
|
205 |
n = len(col_names) |
|
206 |
line_num_skip = 1 |
|
207 |
|
|
201 | 208 |
if not callable(mk_value): |
202 | 209 |
value = mk_value |
203 | 210 |
def mk_value(row, row_num): return value |
204 | 211 |
|
205 | 212 |
def filter_(row): |
206 | 213 |
row = list(row) # make sure it's mutable; don't modify input! |
207 |
for i in xrange(n): |
|
208 |
row.insert(index+i, mk_value(row, self.reader.line_num)) |
|
214 |
|
|
215 |
if self.is_header and col_names != None: |
|
216 |
values = col_names |
|
217 |
self.is_header = False |
|
218 |
else: values = n*[mk_value(row, self.reader.line_num-line_num_skip)] |
|
219 |
|
|
220 |
for i in xrange(len(values)): row.insert(index+i, values[i]) |
|
209 | 221 |
return row |
210 | 222 |
Filter.__init__(self, filter_, |
211 | 223 |
streams.LineCountInputStream(StreamFilter(reader))) |
224 |
self.is_header = True |
|
212 | 225 |
|
213 | 226 |
class RowNumFilter(ColInsertFilter): |
214 | 227 |
'''Adds a row # column at the beginning of each row''' |
Also available in: Unified diff
lib/csvs.py: ColInsertFilter: added support for filtering the header row as well