-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcsvutil.py
46 lines (28 loc) · 888 Bytes
/
csvutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python2
# coding: utf-8
import csv
def to_dicts(data, fields, on_invalid=None):
result = []
if isinstance(data, file):
reader = csv.reader(data)
else:
reader = data
for row in reader:
row_node = {}
for (key, value) in zip(fields, row):
try:
if isinstance(key, (tuple, list,)):
temp = key[1](value)
row_node[key[0]] = temp
else:
row_node[key] = value
except Exception as e:
if on_invalid is 'ignore':
break
elif on_invalid is None:
raise
else:
on_invalid(fields.index(key), key, value, e)
if len(row_node) == len(fields):
result.append(row_node)
return result