|
| 1 | +import os |
| 2 | + |
| 3 | + |
| 4 | +class CSVReader: |
| 5 | + |
| 6 | + def __init__(self, file_path, arguments={'separator': ','}): |
| 7 | + self.__file_path = file_path |
| 8 | + self.__arguments = arguments |
| 9 | + |
| 10 | + self.__initialize() |
| 11 | + |
| 12 | + def __initialize(self): |
| 13 | + """ Prepares and validates argument. """ |
| 14 | + |
| 15 | + if 'separator' not in self.__arguments: |
| 16 | + raise Exception('"separator" argument is required to parse CSV.') |
| 17 | + |
| 18 | + self.__separator = self.__arguments['separator'] |
| 19 | + self.__skip_header = True |
| 20 | + self.__enclosing = '"' |
| 21 | + |
| 22 | + if 'skip_header' in self.__arguments: |
| 23 | + self.__skip_header = self.__arguments['skip_header'] |
| 24 | + if 'enclosing' in self.__arguments: |
| 25 | + self.__enclosing = self.__arguments['enclosing'] |
| 26 | + |
| 27 | + def iterate(self): |
| 28 | + """ allows iteration over parsed data objects with a python generator. """ |
| 29 | + |
| 30 | + with open(self.__file_path) as f: |
| 31 | + for index, line in enumerate(f): |
| 32 | + if index == 0 and self.__skip_header: |
| 33 | + continue |
| 34 | + |
| 35 | + obj = self.__parseLine(line) |
| 36 | + yield obj |
| 37 | + |
| 38 | + def __parseLine(self, line): |
| 39 | + """ Parses a line into python dictionary object """ |
| 40 | + |
| 41 | + split = line.split(self.__separator) |
| 42 | + formatted = [] |
| 43 | + |
| 44 | + if self.__enclosing is not None: |
| 45 | + for entry in split: |
| 46 | + if entry.startswith(self.__enclosing) and entry.endswith(self.__enclosing): |
| 47 | + entry = entry[1:] |
| 48 | + entry = entry[:-1] |
| 49 | + formatted.append(entry) |
| 50 | + |
| 51 | + del split |
| 52 | + |
| 53 | + return formatted |
0 commit comments