one-file-projects/csventry.py

49 lines
1.4 KiB
Python
Raw Permalink Normal View History

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__
)
)
class CSVEntry:
2018-09-17 00:14:40 +02:00
_contents = {}
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
@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 )