1 |
1388
|
aaronmk
|
# CSV I/O
|
2 |
|
|
|
3 |
|
|
import csv
|
4 |
5431
|
aaronmk
|
import _csv
|
5 |
1388
|
aaronmk
|
import StringIO
|
6 |
|
|
|
7 |
1623
|
aaronmk
|
import strings
|
8 |
1444
|
aaronmk
|
import util
|
9 |
|
|
|
10 |
5426
|
aaronmk
|
delims = ',;\t|`'
|
11 |
5439
|
aaronmk
|
tab_padded_delims = ['\t|\t']
|
12 |
1623
|
aaronmk
|
tsv_delim = '\t'
|
13 |
|
|
escape = '\\'
|
14 |
1442
|
aaronmk
|
|
15 |
1623
|
aaronmk
|
ending_placeholder = r'\n'
|
16 |
|
|
|
17 |
5437
|
aaronmk
|
def is_tsv(dialect): return dialect.delimiter.startswith(tsv_delim)
|
18 |
1623
|
aaronmk
|
|
19 |
1621
|
aaronmk
|
def sniff(line):
|
20 |
|
|
'''Automatically detects the dialect'''
|
21 |
5435
|
aaronmk
|
line, ending = strings.extract_line_ending(line)
|
22 |
1623
|
aaronmk
|
dialect = csv.Sniffer().sniff(line, delims)
|
23 |
5435
|
aaronmk
|
|
24 |
5439
|
aaronmk
|
if is_tsv(dialect):
|
25 |
|
|
# TSVs usually don't quote fields (nor doublequote embedded quotes)
|
26 |
|
|
dialect.quoting = csv.QUOTE_NONE
|
27 |
|
|
|
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 |
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 |
1444
|
aaronmk
|
'''Automatically detects the dialect based on the header line
|
41 |
1923
|
aaronmk
|
@return NamedTuple {header_line, header, dialect}'''
|
42 |
1444
|
aaronmk
|
info = util.NamedTuple()
|
43 |
|
|
info.header_line = stream.readline()
|
44 |
1923
|
aaronmk
|
info.header = None
|
45 |
|
|
if info.header_line != '':
|
46 |
|
|
info.dialect = sniff(info.header_line)
|
47 |
|
|
if parse_header:
|
48 |
|
|
info.header = reader_class(info.dialect)(
|
49 |
|
|
StringIO.StringIO(info.header_line), info.dialect).next()
|
50 |
1660
|
aaronmk
|
else: info.dialect = None # line of '' indicates EOF = empty stream
|
51 |
1444
|
aaronmk
|
return info
|
52 |
|
|
|
53 |
5170
|
aaronmk
|
tsv_encode_map = strings.json_encode_map[:]
|
54 |
|
|
tsv_encode_map.append(('\t', r'\t'))
|
55 |
|
|
tsv_decode_map = strings.flip_map(tsv_encode_map)
|
56 |
5146
|
aaronmk
|
|
57 |
1623
|
aaronmk
|
class TsvReader:
|
58 |
|
|
'''Unlike csv.reader, for TSVs, interprets \ as escaping a line ending but
|
59 |
5145
|
aaronmk
|
ignores it before everything else (e.g. \N for NULL).
|
60 |
5170
|
aaronmk
|
Also expands tsv_encode_map escapes.
|
61 |
5145
|
aaronmk
|
'''
|
62 |
1623
|
aaronmk
|
def __init__(self, stream, dialect):
|
63 |
|
|
assert is_tsv(dialect)
|
64 |
|
|
self.stream = stream
|
65 |
|
|
self.dialect = dialect
|
66 |
|
|
|
67 |
|
|
def __iter__(self): return self
|
68 |
|
|
|
69 |
|
|
def next(self):
|
70 |
|
|
record = ''
|
71 |
|
|
ending = None
|
72 |
|
|
while True:
|
73 |
|
|
line = self.stream.readline()
|
74 |
|
|
if line == '': raise StopIteration
|
75 |
|
|
|
76 |
5438
|
aaronmk
|
line = strings.remove_suffix(self.dialect.lineterminator, line)
|
77 |
5433
|
aaronmk
|
contents = strings.remove_suffix(escape, line)
|
78 |
1623
|
aaronmk
|
record += contents
|
79 |
5433
|
aaronmk
|
if len(contents) == len(line): break # no line continuation
|
80 |
1623
|
aaronmk
|
record += ending_placeholder
|
81 |
3055
|
aaronmk
|
|
82 |
|
|
# Prevent "new-line character seen in unquoted field" errors
|
83 |
|
|
record = record.replace('\r', ending_placeholder)
|
84 |
|
|
|
85 |
5429
|
aaronmk
|
row = record.split(self.dialect.delimiter)
|
86 |
5170
|
aaronmk
|
return [strings.replace_all(tsv_decode_map, v) for v in row]
|
87 |
1623
|
aaronmk
|
|
88 |
|
|
def reader_class(dialect):
|
89 |
|
|
if is_tsv(dialect): return TsvReader
|
90 |
|
|
else: return csv.reader
|
91 |
|
|
|
92 |
|
|
def make_reader(stream, dialect): return reader_class(dialect)(stream, dialect)
|
93 |
|
|
|
94 |
1388
|
aaronmk
|
def reader_and_header(stream):
|
95 |
|
|
'''Automatically detects the dialect based on the header line
|
96 |
|
|
@return tuple (reader, header)'''
|
97 |
1923
|
aaronmk
|
info = stream_info(stream, parse_header=True)
|
98 |
1958
|
aaronmk
|
return (make_reader(stream, info.dialect), info.header)
|
99 |
1446
|
aaronmk
|
|
100 |
|
|
##### csv modifications
|
101 |
|
|
|
102 |
|
|
# Note that these methods only work on *instances* of Dialect classes
|
103 |
|
|
csv.Dialect.__eq__ = lambda self, other: self.__dict__ == other.__dict__
|
104 |
|
|
csv.Dialect.__ne__ = lambda self, other: not (self == other)
|
105 |
2114
|
aaronmk
|
|
106 |
5430
|
aaronmk
|
__Dialect__validate_orig = csv.Dialect._validate
|
107 |
|
|
def __Dialect__validate(self):
|
108 |
|
|
try: __Dialect__validate_orig(self)
|
109 |
|
|
except _csv.Error, e:
|
110 |
|
|
if str(e) == '"delimiter" must be an 1-character string': pass # OK
|
111 |
|
|
else: raise
|
112 |
|
|
csv.Dialect._validate = __Dialect__validate
|
113 |
|
|
|
114 |
2114
|
aaronmk
|
##### Row filters
|
115 |
|
|
|
116 |
|
|
class Filter:
|
117 |
|
|
'''Wraps a reader, filtering each row'''
|
118 |
|
|
def __init__(self, filter_, reader):
|
119 |
|
|
self.reader = reader
|
120 |
|
|
self.filter = filter_
|
121 |
|
|
|
122 |
|
|
def __iter__(self): return self
|
123 |
|
|
|
124 |
|
|
def next(self): return self.filter(self.reader.next())
|
125 |
|
|
|
126 |
|
|
std_nulls = [r'\N']
|
127 |
|
|
empty_nulls = [''] + std_nulls
|
128 |
|
|
|
129 |
|
|
class NullFilter(Filter):
|
130 |
|
|
'''Translates special string values to None'''
|
131 |
|
|
def __init__(self, reader, nulls=std_nulls):
|
132 |
|
|
map_ = dict.fromkeys(nulls, None)
|
133 |
|
|
def filter_(row): return [map_.get(v, v) for v in row]
|
134 |
|
|
Filter.__init__(self, filter_, reader)
|
135 |
|
|
|
136 |
|
|
class StripFilter(Filter):
|
137 |
|
|
'''Strips whitespace'''
|
138 |
|
|
def __init__(self, reader):
|
139 |
|
|
def filter_(row): return [v.strip() for v in row]
|
140 |
|
|
Filter.__init__(self, filter_, reader)
|
141 |
5570
|
aaronmk
|
|
142 |
|
|
class ColCtFilter(Filter):
|
143 |
|
|
'''Gives all rows the same # columns'''
|
144 |
|
|
def __init__(self, reader, cols_ct):
|
145 |
|
|
def filter_(row): return util.list_as_length(row, cols_ct)
|
146 |
|
|
Filter.__init__(self, filter_, reader)
|
147 |
5571
|
aaronmk
|
|
148 |
|
|
##### Translators
|
149 |
|
|
|
150 |
|
|
class InputRewriter:
|
151 |
|
|
'''Wraps a reader, writing each row back to CSV'''
|
152 |
|
|
def __init__(self, reader, dialect=csv.excel):
|
153 |
|
|
self.reader = reader
|
154 |
|
|
self.dialect = dialect
|
155 |
|
|
|
156 |
|
|
def readline(self):
|
157 |
|
|
try: row = self.reader.next()
|
158 |
|
|
except StopIteration: return '' # EOF
|
159 |
|
|
line_stream = StringIO.StringIO()
|
160 |
|
|
csv.writer(line_stream, self.dialect).writerow(row)
|
161 |
|
|
return line_stream.getvalue()
|
162 |
|
|
|
163 |
|
|
def read(self, n): return self.readline() # forward all reads to readline()
|