1
|
# CSV I/O
|
2
|
|
3
|
import csv
|
4
|
import _csv
|
5
|
import StringIO
|
6
|
|
7
|
import streams
|
8
|
import strings
|
9
|
import util
|
10
|
|
11
|
delims = ',;\t|`'
|
12
|
tab_padded_delims = ['\t|\t']
|
13
|
tsv_delim = '\t'
|
14
|
escape = '\\'
|
15
|
|
16
|
ending_placeholder = r'\n'
|
17
|
|
18
|
def is_tsv(dialect): return dialect.delimiter.startswith(tsv_delim)
|
19
|
|
20
|
def sniff(line):
|
21
|
'''Automatically detects the dialect'''
|
22
|
line, ending = strings.extract_line_ending(line)
|
23
|
dialect = csv.Sniffer().sniff(line, delims)
|
24
|
|
25
|
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
|
else: dialect.doublequote = True # Sniffer doesn't turn this on by default
|
36
|
dialect.lineterminator = ending
|
37
|
|
38
|
return dialect
|
39
|
|
40
|
def stream_info(stream, parse_header=False):
|
41
|
'''Automatically detects the dialect based on the header line
|
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
|
if parse_header:
|
49
|
info.header = reader_class(info.dialect)(
|
50
|
StringIO.StringIO(info.header_line), info.dialect).next()
|
51
|
else: info.dialect = None # line of '' indicates EOF = empty stream
|
52
|
return info
|
53
|
|
54
|
tsv_encode_map = strings.json_encode_map[:]
|
55
|
tsv_encode_map.append(('\t', r'\t'))
|
56
|
tsv_decode_map = strings.flip_map(tsv_encode_map)
|
57
|
|
58
|
class TsvReader:
|
59
|
'''Unlike csv.reader, for TSVs, interprets \ as escaping a line ending but
|
60
|
ignores it before everything else (e.g. \N for NULL).
|
61
|
Also expands tsv_encode_map escapes.
|
62
|
'''
|
63
|
def __init__(self, stream, dialect):
|
64
|
assert is_tsv(dialect)
|
65
|
self.stream = stream
|
66
|
self.dialect = dialect
|
67
|
|
68
|
def __iter__(self): return self
|
69
|
|
70
|
def next(self):
|
71
|
record = ''
|
72
|
ending = None
|
73
|
while True:
|
74
|
line = self.stream.readline()
|
75
|
if line == '': raise StopIteration
|
76
|
|
77
|
line = strings.remove_suffix(self.dialect.lineterminator, line)
|
78
|
contents = strings.remove_suffix(escape, line)
|
79
|
record += contents
|
80
|
if len(contents) == len(line): break # no line continuation
|
81
|
record += ending_placeholder
|
82
|
|
83
|
# Prevent "new-line character seen in unquoted field" errors
|
84
|
record = record.replace('\r', ending_placeholder)
|
85
|
|
86
|
row = record.split(self.dialect.delimiter)
|
87
|
return [strings.replace_all(tsv_decode_map, v) for v in row]
|
88
|
|
89
|
def reader_class(dialect):
|
90
|
if is_tsv(dialect): return TsvReader
|
91
|
else: return csv.reader
|
92
|
|
93
|
def make_reader(stream, dialect): return reader_class(dialect)(stream, dialect)
|
94
|
|
95
|
def reader_and_header(stream):
|
96
|
'''Automatically detects the dialect based on the header line
|
97
|
@return tuple (reader, header)'''
|
98
|
info = stream_info(stream, parse_header=True)
|
99
|
return (make_reader(stream, info.dialect), info.header)
|
100
|
|
101
|
##### csv modifications
|
102
|
|
103
|
# Note that these methods only work on *instances* of Dialect classes
|
104
|
csv.Dialect.__eq__ = lambda self, other: self.__dict__ == other.__dict__
|
105
|
csv.Dialect.__ne__ = lambda self, other: not (self == other)
|
106
|
|
107
|
__Dialect__validate_orig = csv.Dialect._validate
|
108
|
def __Dialect__validate(self):
|
109
|
try: __Dialect__validate_orig(self)
|
110
|
except _csv.Error, e:
|
111
|
if str(e) == '"delimiter" must be an 1-character string': pass # OK
|
112
|
else: raise
|
113
|
csv.Dialect._validate = __Dialect__validate
|
114
|
|
115
|
##### Row filters
|
116
|
|
117
|
class Filter:
|
118
|
'''Wraps a reader, filtering each row'''
|
119
|
def __init__(self, filter_, reader):
|
120
|
self.reader = reader
|
121
|
self.filter = filter_
|
122
|
|
123
|
def __iter__(self): return self
|
124
|
|
125
|
def next(self): return self.filter(self.reader.next())
|
126
|
|
127
|
def close(self): pass # support using as a stream
|
128
|
|
129
|
std_nulls = [r'\N']
|
130
|
empty_nulls = [''] + std_nulls
|
131
|
|
132
|
class NullFilter(Filter):
|
133
|
'''Translates special string values to None'''
|
134
|
def __init__(self, reader, nulls=std_nulls):
|
135
|
map_ = dict.fromkeys(nulls, None)
|
136
|
def filter_(row): return [map_.get(v, v) for v in row]
|
137
|
Filter.__init__(self, filter_, reader)
|
138
|
|
139
|
class StripFilter(Filter):
|
140
|
'''Strips whitespace'''
|
141
|
def __init__(self, reader):
|
142
|
def filter_(row): return [v.strip() for v in row]
|
143
|
Filter.__init__(self, filter_, reader)
|
144
|
|
145
|
class ColCtFilter(Filter):
|
146
|
'''Gives all rows the same # columns'''
|
147
|
def __init__(self, reader, cols_ct):
|
148
|
def filter_(row): return util.list_as_length(row, cols_ct)
|
149
|
Filter.__init__(self, filter_, reader)
|
150
|
|
151
|
##### Translators
|
152
|
|
153
|
class StreamFilter(Filter):
|
154
|
'''Wraps a reader in a way that's usable to a filter stream that does not
|
155
|
require lines to be strings. Reports EOF as '' instead of StopIteration.'''
|
156
|
def __init__(self, reader):
|
157
|
Filter.__init__(self, None, reader)
|
158
|
|
159
|
def readline(self):
|
160
|
try: return self.reader.next()
|
161
|
except StopIteration: return '' # EOF
|
162
|
|
163
|
class RowNumFilter(Filter):
|
164
|
'''Adds a row # column at the beginning of each row'''
|
165
|
def __init__(self, reader):
|
166
|
def filter_(row): return [self.reader.line_num]+row
|
167
|
Filter.__init__(self, filter_,
|
168
|
streams.LineCountInputStream(StreamFilter(reader)))
|
169
|
|
170
|
class InputRewriter(StreamFilter):
|
171
|
'''Wraps a reader, writing each row back to CSV'''
|
172
|
def __init__(self, reader, dialect=csv.excel):
|
173
|
StreamFilter.__init__(self, reader)
|
174
|
|
175
|
self.dialect = dialect
|
176
|
|
177
|
def readline(self):
|
178
|
row = self.reader.readline()
|
179
|
if row == '': return row # EOF
|
180
|
|
181
|
line_stream = StringIO.StringIO()
|
182
|
csv.writer(line_stream, self.dialect).writerow(row)
|
183
|
return line_stream.getvalue()
|
184
|
|
185
|
def read(self, n): return self.readline() # forward all reads to readline()
|