重组CSV文件?

时间:2013-12-01 20:49:13

标签: javascript python bash csv

我有基本的脚本知识,但我不确定如何解决这个问题。我正在尝试将我的银行自动生成的CSV文件转换为YNAB(您需要预算)可以理解的格式。

YNAB格式(所需的csv文件格式)

Date,Payee,Category,Memo,Outflow,Inflow
07/25/10,Sample Payee,,Sample Memo for an outflow,100.00,
07/26/10,Sample Payee 2,,Sample memo for an inflow,,500.00

银行格式(csv文件的当前状态)

"Account Type","Account Number","Transaction Date","Cheque Number","Description 1","Description 2","CAD$","USD$"
Chequing,00401-1234567,8/19/2013,,"Transfer","WWW TRANSFER - 0645 ",50.00,,
Chequing,00401-1234567,8/19/2013,,"STARBUCKS AC. U","IDP PURCHASE - 6678 ",-1.94,,

(所有假数据)

如何将当前的CSV文件转换为所需格式?

2 个答案:

答案 0 :(得分:1)

这应该做:

import csv
import sys

if sys.hexversion >= 0x3000000:
    inp = input
else:
    inp = raw_input

def main():
    input_file  = inp('Name of bank statement file? ')
    output_file = inp('Save YNAB output file as? ')

    with open(input_file, 'rb') as inf, open(output_file, 'wb') as outf:
        incsv  = csv.reader(inf)
        outcsv = csv.write(outf)
        # deal with headers
        header = next(incsv)
        outcsv.write(['Date', 'Payee', 'Category', 'Memo', 'Outflow', 'Inflow'])
        # translate data
        for row in incsv:
            cad = float(row[6])
            ynab = [row[2], row[4], '', row[5], -cad if cad < 0. else '', cad if cad > 0. else '']
            outcsv.writerow(ynab)

if __name__=="__main__":
    main()

答案 1 :(得分:-1)

我强烈建议您在此任务中提升(甚至开始)您的python scrpiting技能。

首先学习如何读取文件并将其拆分为多个部分(列表列表)。 然后练习打印值,然后打印整个输出行(使用正确重新排序的值)。

然后撒上一些排序逻辑,以便在需要的条件下输出各种线条。