Как преобразовать список кортежей в CSV-файл - PullRequest
0 голосов
/ 08 февраля 2020

Очень плохо знаком с программированием и пытался создать таблицу амортизации. Нашел здесь несколько замечательных вопросов и ответов, но теперь я застрял, пытаясь преобразовать результаты в файл CSV.

from datetime import date
from collections import OrderedDict
from dateutil.relativedelta import *
import csv

def amortization_schedule(rate, principal, period):
start_date=date.today()
#defining the monthly payment for a loan
payment = -float(principal / ((((1 + (rate / 12)) ** period) - 1) / ((rate / 12) * (1 + (rate / 12)) ** period)))

beg_balance = principal
end_balance = principal
period = 1


while end_balance > 0 and period <= 60 * 12:

    #Recalculate the interest based on the current balance
    interest_paid = round((rate / 12) * beg_balance, 2)

    #Determine payment based on whether or not this period will pay off the loan
    payment = round(min(payment, beg_balance + interest_paid), 2)
    principal = round(-payment - interest_paid, 2)


    yield OrderedDict([('Month', start_date),
                       ('Period', period),
                       ('Begin Balance', beg_balance),
                       ('Payment', payment),
                       ('Principal', principal),
                       ('Interest', interest_paid),
                       ('End Balance', end_balance)])


    #increment the counter, date and balance
    period +=1
    start_date += relativedelta(months=1)
    beg_balance = end_balance     

Я пытался использовать эту ссылку как часть моего решения, но в итоге получился CSV, который выглядел следующим образом:

M,o,n,t,h
P,e,r,i,o,d
B,e,g,i,n, ,B,a,l,a,n,c,e
P,a,y,m,e,n,t
P,r,i,n,c,i,p,a,l
I,n,t,e,r,e,s,t
E,n,d, ,B,a,l,a,n,c,e

Вот мой код для преобразования в CSV.

for start_date, period, beg_balance, payment, principal, 
  interest_paid, end_balance in amortization_schedule(user_rate, 
  user_principal, user_period):
  start_dates.append(start_date)
  periods.append(period)
  beg_balances.append(beg_balance)
  payments.append(payment)
  principals.append(principal)
  interest_paids.append(interest_paid)
  end_balances.append(end_balance)
with open('amortization.csv', 'w') as outfile: 
  csvwriter = csv.writer(outfile)
  csvwriter.writerow(start_dates)
  csvwriter.writerow(periods)
  csvwriter.writerow(beg_balances)
  csvwriter.writerow(payments)
  csvwriter.writerow(principals)
  csvwriter.writerow(interest_paids)
  csvwriter.writerow(end_balances)

Любая помощь будет оценена!

1 Ответ

0 голосов
/ 08 февраля 2020
with open('amortization.csv', 'w', newline='') as outfile:
    fieldnames = ['Month', 'Period', 'Begin Balance', 'Payment',
                  'Principal', 'Interest', 'End Balance']

    csvwriter = csv.DictWriter(outfile, fieldnames)

    for line in amortization_schedule(user_rate, user_principal, user_period):
        csvwriter.writerow(line)

Код для записи файла CSV.

collections.OrderedDict - это словарь, поэтому, возможно, потребуется использовать csv.DictWriter для написания словаря. Это словарь, поэтому вам не нужны все строки, которые есть у вас для преобразования в csv.

...