Project

General

Profile

1 1388 aaronmk
# CSV I/O
2
3
import csv
4 5431 aaronmk
import _csv
5 1388 aaronmk
import StringIO
6
7 5593 aaronmk
import streams
8 1623 aaronmk
import strings
9 1444 aaronmk
import util
10
11 5426 aaronmk
delims = ',;\t|`'
12 5439 aaronmk
tab_padded_delims = ['\t|\t']
13 1623 aaronmk
tsv_delim = '\t'
14
escape = '\\'
15 1442 aaronmk
16 1623 aaronmk
ending_placeholder = r'\n'
17
18 5437 aaronmk
def is_tsv(dialect): return dialect.delimiter.startswith(tsv_delim)
19 1623 aaronmk
20 1621 aaronmk
def sniff(line):
21
    '''Automatically detects the dialect'''
22 5435 aaronmk
    line, ending = strings.extract_line_ending(line)
23 1623 aaronmk
    dialect = csv.Sniffer().sniff(line, delims)
24 5435 aaronmk
25 5439 aaronmk
    if is_tsv(dialect):
26
        # TSVs usually don't quote fields (nor doublequote embedded quotes)
27
        dialect.quoting = csv.QUOTE_NONE
28
29
        # Check multi-char delims using \t
30
        delim = strings.find_any(line, tab_padded_delims)
31
        if delim:
32
            dialect.delimiter = delim
33
            line_suffix = delim.rstrip('\t')
34
            if line.endswith(line_suffix): ending = line_suffix+ending
35 1621 aaronmk
    else: dialect.doublequote = True # Sniffer doesn't turn this on by default
36 5435 aaronmk
    dialect.lineterminator = ending
37
38 1621 aaronmk
    return dialect
39
40 1923 aaronmk
def stream_info(stream, parse_header=False):
41 6589 aaronmk
    '''Automatically detects the dialect based on the header line.
42
    Uses the Excel dialect if the CSV file is empty.
43 1923 aaronmk
    @return NamedTuple {header_line, header, dialect}'''
44 1444 aaronmk
    info = util.NamedTuple()
45
    info.header_line = stream.readline()
46 1923 aaronmk
    info.header = None
47
    if info.header_line != '':
48
        info.dialect = sniff(info.header_line)
49 6589 aaronmk
    else: info.dialect = csv.excel # line of '' indicates EOF = empty stream
50
51
    if parse_header:
52
        try: info.header = reader_class(info.dialect)(
53
            StringIO.StringIO(info.header_line), info.dialect).next()
54
        except StopIteration: info.header = []
55
56 1444 aaronmk
    return info
57
58 5170 aaronmk
tsv_encode_map = strings.json_encode_map[:]
59
tsv_encode_map.append(('\t', r'\t'))
60
tsv_decode_map = strings.flip_map(tsv_encode_map)
61 5146 aaronmk
62 1623 aaronmk
class TsvReader:
63
    '''Unlike csv.reader, for TSVs, interprets \ as escaping a line ending but
64 5145 aaronmk
    ignores it before everything else (e.g. \N for NULL).
65 5170 aaronmk
    Also expands tsv_encode_map escapes.
66 5145 aaronmk
    '''
67 1623 aaronmk
    def __init__(self, stream, dialect):
68
        assert is_tsv(dialect)
69
        self.stream = stream
70
        self.dialect = dialect
71
72
    def __iter__(self): return self
73
74
    def next(self):
75
        record = ''
76
        ending = None
77
        while True:
78
            line = self.stream.readline()
79
            if line == '': raise StopIteration
80
81 5438 aaronmk
            line = strings.remove_suffix(self.dialect.lineterminator, line)
82 5433 aaronmk
            contents = strings.remove_suffix(escape, line)
83 1623 aaronmk
            record += contents
84 5433 aaronmk
            if len(contents) == len(line): break # no line continuation
85 1623 aaronmk
            record += ending_placeholder
86 3055 aaronmk
87
        # Prevent "new-line character seen in unquoted field" errors
88
        record = record.replace('\r', ending_placeholder)
89
90 5429 aaronmk
        row = record.split(self.dialect.delimiter)
91 5170 aaronmk
        return [strings.replace_all(tsv_decode_map, v) for v in row]
92 1623 aaronmk
93
def reader_class(dialect):
94
    if is_tsv(dialect): return TsvReader
95
    else: return csv.reader
96
97
def make_reader(stream, dialect): return reader_class(dialect)(stream, dialect)
98
99 1388 aaronmk
def reader_and_header(stream):
100
    '''Automatically detects the dialect based on the header line
101
    @return tuple (reader, header)'''
102 1923 aaronmk
    info = stream_info(stream, parse_header=True)
103 1958 aaronmk
    return (make_reader(stream, info.dialect), info.header)
104 1446 aaronmk
105
##### csv modifications
106
107
# Note that these methods only work on *instances* of Dialect classes
108
csv.Dialect.__eq__ = lambda self, other: self.__dict__ == other.__dict__
109
csv.Dialect.__ne__ = lambda self, other: not (self == other)
110 2114 aaronmk
111 5430 aaronmk
__Dialect__validate_orig = csv.Dialect._validate
112
def __Dialect__validate(self):
113
        try: __Dialect__validate_orig(self)
114
        except _csv.Error, e:
115
            if str(e) == '"delimiter" must be an 1-character string': pass # OK
116
            else: raise
117
csv.Dialect._validate = __Dialect__validate
118
119 2114 aaronmk
##### Row filters
120
121
class Filter:
122
    '''Wraps a reader, filtering each row'''
123
    def __init__(self, filter_, reader):
124
        self.reader = reader
125
        self.filter = filter_
126
127
    def __iter__(self): return self
128
129
    def next(self): return self.filter(self.reader.next())
130 5574 aaronmk
131
    def close(self): pass # support using as a stream
132 2114 aaronmk
133
std_nulls = [r'\N']
134
empty_nulls = [''] + std_nulls
135
136
class NullFilter(Filter):
137
    '''Translates special string values to None'''
138
    def __init__(self, reader, nulls=std_nulls):
139
        map_ = dict.fromkeys(nulls, None)
140
        def filter_(row): return [map_.get(v, v) for v in row]
141
        Filter.__init__(self, filter_, reader)
142
143
class StripFilter(Filter):
144
    '''Strips whitespace'''
145
    def __init__(self, reader):
146
        def filter_(row): return [v.strip() for v in row]
147
        Filter.__init__(self, filter_, reader)
148 5570 aaronmk
149
class ColCtFilter(Filter):
150
    '''Gives all rows the same # columns'''
151
    def __init__(self, reader, cols_ct):
152
        def filter_(row): return util.list_as_length(row, cols_ct)
153
        Filter.__init__(self, filter_, reader)
154 5571 aaronmk
155
##### Translators
156
157 5586 aaronmk
class StreamFilter(Filter):
158
    '''Wraps a reader in a way that's usable to a filter stream that does not
159
    require lines to be strings. Reports EOF as '' instead of StopIteration.'''
160
    def __init__(self, reader):
161
        Filter.__init__(self, None, reader)
162
163
    def readline(self):
164
        try: return self.reader.next()
165
        except StopIteration: return '' # EOF
166
167 5735 aaronmk
class ColInsertFilter(Filter):
168
    '''Adds a column to each row
169
    @param mk_value(row, row_num)
170
    '''
171
    def __init__(self, reader, mk_value, index=0):
172
        def filter_(row):
173
            row = list(row) # make sure it's mutable; don't modify input!
174
            row.insert(index, mk_value(row, self.reader.line_num))
175
            return row
176
        Filter.__init__(self, filter_,
177
            streams.LineCountInputStream(StreamFilter(reader)))
178
179 5736 aaronmk
class RowNumFilter(ColInsertFilter):
180 5593 aaronmk
    '''Adds a row # column at the beginning of each row'''
181
    def __init__(self, reader):
182 5736 aaronmk
        def mk_value(row, row_num): return row_num
183
        ColInsertFilter.__init__(self, reader, mk_value, 0)
184 5593 aaronmk
185 5587 aaronmk
class InputRewriter(StreamFilter):
186 5571 aaronmk
    '''Wraps a reader, writing each row back to CSV'''
187
    def __init__(self, reader, dialect=csv.excel):
188 5587 aaronmk
        StreamFilter.__init__(self, reader)
189
190 5571 aaronmk
        self.dialect = dialect
191
192
    def readline(self):
193 5587 aaronmk
        row = self.reader.readline()
194 5585 aaronmk
        if row == '': return row # EOF
195
196 5571 aaronmk
        line_stream = StringIO.StringIO()
197
        csv.writer(line_stream, self.dialect).writerow(row)
198
        return line_stream.getvalue()
199
200
    def read(self, n): return self.readline() # forward all reads to readline()