-
Notifications
You must be signed in to change notification settings - Fork 1
/
mycsv.py
75 lines (56 loc) · 1.56 KB
/
mycsv.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'''
functions relating to csv type files
containing data in generic tabular form
'''
def save_csv(data,fname,sep=','):
'''
save data to generic tabular format
'''
f = open(fname,"wb")
for row in data:
f.write(sep.join([str(x) for x in row]) + '\n')
f.close()
def load_csv(fname,sep=',',strip_data=True):
'''
load in data into a list of lists
return header lines separately
'''
f = open(fname,"rb")
data = [line.strip().split(sep) for line in f]
f.close()
#remove whitespace from data
if strip_data:
for row in data:
for i,x in enumerate(row):
row[i] = x.strip()
#return data without a header
return data
def reorder_columns(data,order,missing=-1,reverse=False):
'''
reorder columns according to given heading order
'''
order_dict = {}
for i,x in enumerate(order): order_dict[x] = i
data = transpose_table(data)
#append correct ordering
for row in data:
if row[0] in order_dict:
row.append(order_dict[row[0]])
else:
row.append(missing)
data.sort(key=lambda x:x[-1],reverse=reverse)
#remove ordering value
for row in data: del row[-1]
return transpose_table(data)
def sort_columns(data,func):
'''
sort table columns using func
'''
data = transpose_table(data)
data.sort(key=func)
return transpose_table(data)
def transpose_table(data):
'''
transpose the list of lists
'''
return map(list,zip(*data))