正在重新构造CSV文件

Restructing a CSV file?

本文关键字:CSV 文件 新构造      更新时间:2024-02-02

我有基本的脚本知识,但我不知道如何解决这个问题。我正在尝试将我的银行自动生成的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文件转换为所需格式?

这应该做:

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()

我强烈鼓励你在这项任务中提高(甚至开始)你的python抓取技能。

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

然后加入一些排序逻辑,以便根据需要的条件输出各种行。