Advertisement
siverpro

csvreader

Jul 22nd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. import csv
  2.  
  3.  
  4. class CsvReader(object):
  5.     def __init__(
  6.         self,
  7.         csv_file=None):
  8.         self.csv_file = str(csv_file) if csv_file else None
  9.         self.dict_list = []
  10.         self.read_file()
  11.  
  12.     def read_file(self):
  13.         with open(self.csv_file, newline='') as csvfile:
  14.             reader = csv.DictReader(csvfile, delimiter=',')
  15.             for row in reader:
  16.                 self.dict_list.append(row)
  17.  
  18.     def list_incomes(self):
  19.         filtered = []
  20.         for row in self.dict_list:
  21.             temp_dict = {}
  22.             temp_dict['dato'] = row['Date Acquired']
  23.             temp_dict['verdi'] = row['Cost Basis']
  24.             temp_dict['comment'] = 'Inntekt: ' + row['Volume'] + ' ' + row['Symbol']
  25.             filtered.append(temp_dict)
  26.         return filtered
  27.         # do something with the row
  28.         #print(row['Date Acquired'], int(float(row['Cost Basis']) * 100), row['Currency'], comment)
  29.  
  30.     def list_sales(self):
  31.         date = None
  32.         sale_sum = float(0)
  33.         filtered = []
  34.         for row in self.dict_list:
  35.             if row['Date Sold']:
  36.                 if date == row['Date Sold']: # If the same date, add value to sum
  37.                     sale_sum += float(row['Gain'])
  38.                 else: # if a NEW UNIQUE non-empty date is encountered, add the current sum to list and start a new line
  39.                     if date != None:
  40.                         filtered.append({'dato': date, 'gain': sale_sum})
  41.                     date = row['Date Sold']
  42.                     sale_sum = float(row['Gain'])
  43.         if sale_sum != float(0): # finally, add the sum as the last item in the list
  44.             filtered.append({'dato': date, 'gain': sale_sum})
  45.         return filtered
  46.  
  47. reader = CsvReader('2018_gains.csv')
  48. print(reader.list_incomes())
  49. print(reader.list_sales())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement