48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
import csv
|
|
|
|
class CSVFieldUnknown(Exception):
|
|
def __init__(self, cls, field):
|
|
super(CSVFieldUnknown, self).__init__(
|
|
"Unknown field %s for class %s" % (
|
|
field,
|
|
cls.__name__
|
|
)
|
|
)
|
|
|
|
class CSVEntry:
|
|
_contents = {}
|
|
def __init__(self, **kvargs):
|
|
for field in self.__class__.fields:
|
|
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 )
|