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