【问题标题】:How to convert a list of tuples to a csv file如何将元组列表转换为 csv 文件
【发布时间】:2020-05-24 04:44:52
【问题描述】:

对编程非常陌生,正在尝试创建摊销表。在这里找到了一些很棒的问题和答案,但现在我一直在尝试将结果转换为 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     

我尝试使用 this link 作为我的解决方案的一部分,但最终得到了一个如下所示的 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)

任何帮助将不胜感激!

【问题讨论】:

    标签: python-3.x csv generator export-to-csv ordereddictionary


    【解决方案1】:
    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 的行。

    【讨论】: