-
Notifications
You must be signed in to change notification settings - Fork 0
/
csvsimple.py
41 lines (32 loc) · 932 Bytes
/
csvsimple.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
# SimpleCSV Class
import csv
class SimpleCSV:
def __init__(self, filename):
with open(filename, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
self.filename = filename
self.keys = reader.fieldnames
self.data = []
for row in reader:
self.data.append(row)
def __len__(self):
return len(self.data)
def __getitem__(self, key):
return self.data[key]
def __iter__(self):
for d in self.data:
yield d
def save(self, filename=False):
if not filename:
filename = self.filename
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, self.keys)
writer.writeheader()
writer.writerows(self.data)
def csv_to_dict(filename):
d = dict()
with open(filename, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for key, val in reader:
d[key] = val
return d