2018-09-16 23:40:27 +02:00
|
|
|
import csv
|
|
|
|
|
2018-09-17 00:14:40 +02:00
|
|
|
class CSVFieldUnknown(Exception):
|
|
|
|
def __init__(self, cls, field):
|
|
|
|
super(CSVFieldUnknown, self).__init__(
|
|
|
|
"Unknown field %s for class %s" % (
|
|
|
|
field,
|
|
|
|
cls.__name__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2018-09-16 23:40:27 +02:00
|
|
|
class CSVEntry:
|
2018-09-17 00:14:40 +02:00
|
|
|
_contents = {}
|
2018-09-16 23:40:27 +02:00
|
|
|
def __init__(self, **kvargs):
|
|
|
|
for field in self.__class__.fields:
|
2018-09-17 00:14:40 +02:00
|
|
|
setattr(self, field, "")
|
|
|
|
for field, val in kvargs.items():
|
|
|
|
setattr(self, field, val)
|
|
|
|
|
|
|
|
def __getattr__(self, key):
|
|
|
|
if key not in self.__class__.fields:
|
|
|
|
raise CSVFieldUnknown(self.__class__, key)
|
|
|
|
return self._contents[key]
|
|
|
|
|
|
|
|
def __setattr__(self, key, value):
|
|
|
|
if key not in self.__class__.fields:
|
|
|
|
raise CSVFieldUnknown(self.__class__, key)
|
|
|
|
self._contents[key] = value
|
2018-09-16 23:40:27 +02:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def fromRow(cls, row):
|
|
|
|
assert len(row) == len(cls.fields)
|
|
|
|
return cls(**{ field : value for field,value in zip(cls.fields, row)})
|
|
|
|
|
|
|
|
def toRow(self):
|
|
|
|
return list(getattr(self,field) for field in self.__class__.fields)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def loadFile(cls, file):
|
|
|
|
with open(file) as csvfile:
|
|
|
|
reader = csv.reader(csvfile)
|
|
|
|
return list( cls.fromRow(row) for row in reader )
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def saveFile(file, entries):
|
|
|
|
with open(file,"w") as csvfile:
|
|
|
|
writer = csv.writer(csvfile)
|
|
|
|
writer.writerows( entry.toRow() for entry in entries )
|