27 lines
887 B
Python
27 lines
887 B
Python
import csv
|
|
|
|
class CSVEntry:
|
|
def __init__(self, **kvargs):
|
|
assert ( set(kvargs.keys()) - set(self.__class__.fields) ) == set()
|
|
for field in self.__class__.fields:
|
|
setattr(self, field, kvargs[field] or "")
|
|
|
|
@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 )
|