-
Notifications
You must be signed in to change notification settings - Fork 22
/
readcsv.py
39 lines (33 loc) · 1.03 KB
/
readcsv.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
"""
readcsv.py
"""
import csv
from collections import OrderedDict
def readcsv(file, **fmtparams):
"""
Read a CSV from the file, and return it as an ordered dict.
We assume the first line contains all the key names.
Empty row elements are converted to None.
Any column that has an empty key name is added to a list with key `_misc`.
Any column with empty key and row element is ignored.
"""
keys = None
rows = []
reader = csv.reader(file, **fmtparams)
for row in reader:
if not keys:
keys = row
else:
r = OrderedDict()
assert len(keys) == len(row)
for k, v in zip(keys, row):
if not k or k == "":
if not v or v == "": continue
if "_misc" not in r: r["_misc"] = []
r["_misc"].append(v)
else:
assert k not in r
if not v or v == "": v = None
r[k] = v
rows.append(r)
return rows