From e56c6ca585a6182ed536f8c53bf3aabcb1d9c12d Mon Sep 17 00:00:00 2001 From: Mad Date: Sun, 16 Sep 2018 23:40:27 +0200 Subject: [PATCH] Add helper class for easy csv file access with defined rows --- csventry.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 csventry.py diff --git a/csventry.py b/csventry.py new file mode 100644 index 0000000..c6cba52 --- /dev/null +++ b/csventry.py @@ -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 )