Add csv_parser
This commit is contained in:
parent
b5bf76908a
commit
8ac1513873
64
csv_parser.py
Normal file
64
csv_parser.py
Normal file
@ -0,0 +1,64 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import io
|
||||
|
||||
|
||||
class CSVHandler:
|
||||
"""
|
||||
parse given csv
|
||||
"""
|
||||
def __init__(self, path):
|
||||
"""
|
||||
:param path: path to file
|
||||
"""
|
||||
self.file = io.open(path, "r", encoding="cp1251").read().split("\n")
|
||||
self.headers = ['date', 'sum', 'category']
|
||||
|
||||
def get_row(self, row):
|
||||
""" Get row with given index
|
||||
:param row:
|
||||
:return:
|
||||
"""
|
||||
|
||||
return self.file[row]
|
||||
|
||||
def check_row(self, row_index, **kwargs):
|
||||
""" Check that row has given values
|
||||
:param row_index:
|
||||
:param kwargs:
|
||||
:return: True if values coincides else False
|
||||
"""
|
||||
i = self.get_row(row_index).split(";")
|
||||
for key, val in kwargs.items():
|
||||
index = self.headers.index(key)
|
||||
if i[index] != val:
|
||||
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def find_row(self, value=None, **kwargs):
|
||||
""" Find row index of row containing given values
|
||||
:param kwargs:
|
||||
:return: index of row if it is found, else None
|
||||
"""
|
||||
if value is not None:
|
||||
|
||||
return 0
|
||||
|
||||
for i in range(len(self.file)-1):
|
||||
if self.check_row(i, **kwargs):
|
||||
|
||||
return i
|
||||
|
||||
def get_row_data(self, value=None, **kwargs):
|
||||
""" Find row containing given values and take dict with all values that it has
|
||||
:param kwargs:
|
||||
:return:
|
||||
"""
|
||||
|
||||
row = self.find_row(value, **kwargs)
|
||||
|
||||
data = self.file[row].split(";")
|
||||
|
||||
return dict(zip(self.headers, data))
|
Loading…
Reference in New Issue
Block a user