Add helper class for easy csv file access with defined rows

This commit is contained in:
madmaurice 2018-09-16 23:40:27 +02:00
parent 77c444139b
commit e56c6ca585

27
csventry.py Normal file
View file

@ -0,0 +1,27 @@
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 )