From 7cd2169829fde56c8967b29985c88a02b313bec8 Mon Sep 17 00:00:00 2001 From: Valentin Gehrke Date: Thu, 12 Oct 2017 07:36:12 +0200 Subject: [PATCH] CSV iterator --- csv.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 csv.py diff --git a/csv.py b/csv.py new file mode 100644 index 0000000..54dd43f --- /dev/null +++ b/csv.py @@ -0,0 +1,43 @@ + +class CSVFile(object): + def __init__(self, filename): + self.filename = filename + + def __iter__(self): + return CSVFileIterator(open(self.filename,"r")) + +class CSVFileIterator(object): + def __init__(self, fh): + self.fh = fh + self.lines = iter(fh.readlines()) + + def __next__(self): + return CSVEntry(next(self.lines)) + +class CSVEntry(object): + def __init__(self,line): + self.data = line.split(";") + + def getInt(self, index): + return int(self.data[index]) + + def getFloat(self, index): + return float(self.data[index]) + + def getString(self, index): + return self.data[index] + + def __getitem__(self, index): + return self.getString(index) + + def __iter__(self): + return iter(self.data) + + def __len__(self): + return len(self.data) + +if __name__ == "__main__": + from sys import argv + for entry in CSVFile(argv[1]): + for field in entry: + print("%10s" % field, end="")