Project

General

Profile

1
# CSV I/O
2

    
3
import csv
4
import _csv
5
import StringIO
6

    
7
import exc
8
import streams
9
import strings
10
import util
11

    
12
delims = ',;\t|`'
13
tab_padded_delims = ['\t|\t']
14
tsv_delim = '\t'
15
escape = '\\'
16

    
17
ending_placeholder = r'\n'
18

    
19
def is_tsv(dialect): return dialect.delimiter.startswith(tsv_delim)
20

    
21
def sniff(line):
22
    '''Automatically detects the dialect'''
23
    line, ending = strings.extract_line_ending(line)
24
    dialect = csv.Sniffer().sniff(line, delims)
25
    
26
    if is_tsv(dialect):
27
        dialect.quoting = csv.QUOTE_NONE
28
        # 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
    else: dialect.doublequote = True # Sniffer doesn't turn this on by default
35
    dialect.lineterminator = ending
36
    
37
    return dialect
38

    
39
def stream_info(stream, parse_header=False):
40
    '''Automatically detects the dialect based on the header line.
41
    Uses the Excel dialect if the CSV file is empty.
42
    @return NamedTuple {header_line, header, dialect}'''
43
    info = util.NamedTuple()
44
    info.header_line = stream.readline()
45
    info.header = None
46
    if info.header_line != '':
47
        info.dialect = sniff(info.header_line)
48
    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
    return info
56

    
57
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

    
61
class TsvReader:
62
    '''Unlike csv.reader, for TSVs, interprets \ as escaping a line ending but
63
    ignores it before everything else (e.g. \N for NULL).
64
    Also expands tsv_encode_map escapes.
65
    '''
66
    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
            line = strings.remove_suffix(self.dialect.lineterminator, line)
81
            contents = strings.remove_suffix(escape, line)
82
            record += contents
83
            if len(contents) == len(line): break # no line continuation
84
            record += ending_placeholder
85
        
86
        # Prevent "new-line character seen in unquoted field" errors
87
        record = record.replace('\r', ending_placeholder)
88
        
89
        # Split line
90
        if record == '': row = [] # csv.reader would interpret as EOF
91
        elif len(self.dialect.delimiter) > 1: # multi-char delims
92
            row = record.split(self.dialect.delimiter)
93
        else: row = csv.reader(StringIO.StringIO(record), self.dialect).next()
94
        
95
        return [strings.replace_all(tsv_decode_map, v) for v in row]
96

    
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
def reader_and_header(stream):
104
    '''Automatically detects the dialect based on the header line
105
    @return tuple (reader, header)'''
106
    info = stream_info(stream, parse_header=True)
107
    return (make_reader(stream, info.dialect), info.header)
108

    
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

    
115
__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
##### 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
    
135
    def close(self): pass # support using as a stream
136

    
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

    
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

    
159
##### Translators
160

    
161
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
class ColInsertFilter(Filter):
172
    '''Adds column(s) to each row
173
    @param mk_value(row, row_num)
174
    '''
175
    def __init__(self, reader, mk_value, index=0, n=1):
176
        def filter_(row):
177
            row = list(row) # make sure it's mutable; don't modify input!
178
            for i in xrange(n):
179
                row.insert(index+i, mk_value(row, self.reader.line_num))
180
            return row
181
        Filter.__init__(self, filter_,
182
            streams.LineCountInputStream(StreamFilter(reader)))
183

    
184
class RowNumFilter(ColInsertFilter):
185
    '''Adds a row # column at the beginning of each row'''
186
    def __init__(self, reader):
187
        def mk_value(row, row_num): return row_num
188
        ColInsertFilter.__init__(self, reader, mk_value, 0)
189

    
190
class InputRewriter(StreamFilter):
191
    '''Wraps a reader, writing each row back to CSV'''
192
    def __init__(self, reader, dialect=csv.excel):
193
        StreamFilter.__init__(self, reader)
194
        
195
        self.dialect = dialect
196
    
197
    def readline(self):
198
        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
    
209
    def read(self, n): return self.readline() # forward all reads to readline()
(10-10/47)