Add helper class for easy csv file access with defined rows
This commit is contained in:
parent
77c444139b
commit
e56c6ca585
1 changed files with 27 additions and 0 deletions
27
csventry.py
Normal file
27
csventry.py
Normal 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 )
|
Loading…
Reference in a new issue