-
Notifications
You must be signed in to change notification settings - Fork 2
/
oplcsv.py
70 lines (56 loc) · 2.07 KB
/
oplcsv.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
#!/usr/bin/env python3
# vim: set ts=8 sts=4 et sw=4 tw=99:
#
# A better CSV manipulation library for the OpenPowerlifting format.
#
class Csv:
def __init__(self, filename=None):
if filename:
with open(filename, 'r') as fd:
self.fieldnames = fd.readline().rstrip().split(',')
self.rows = [x.strip().split(',') for x in fd.readlines()]
else:
self.fieldnames = []
self.rows = []
def __len__(self):
return len(self.rows)
def index(self, name):
return self.fieldnames.index(name)
def append_column(self, name):
self.fieldnames.append(name)
for row in self.rows:
row.append('')
def append_columns(self, namelist):
self.fieldnames += namelist
addend = ['' for x in namelist]
for row in self.rows:
row += addend
def insert_column(self, index, name):
self.fieldnames.insert(index, name)
for row in self.rows:
row.insert(index, '')
def remove_column_by_index(self, idx):
del self.fieldnames[idx]
for row in self.rows:
del row[idx]
def remove_column_by_name(self, name):
for i, header in enumerate(self.fieldnames):
if header == name:
self.remove_column_by_index(i)
return
# Integrate another Csv object into the current one.
def cat(self, other):
for header in other.fieldnames:
if not header in self.fieldnames:
self.append_column(header)
# An array mapping index in other.fieldnames to index in self.fieldnames.
mapping = [self.index(header) for header in other.fieldnames]
for row in other.rows:
build = ['' for x in range(0, len(self.fieldnames))]
for i, cell in enumerate(row):
build[mapping[i]] = cell
self.rows.append(build)
def write(self, fd):
fd.write(','.join(self.fieldnames) + "\n")
for row in self.rows:
fd.write(','.join(map(str, row)) + "\n")