重建CSV文件?

2024-04-28 16:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件csvsampleannumberfordate格式
2条回答

这应该做到:

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 scrpiting技能。你知道吗

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

然后加入一些排序逻辑,以便根据需要的条件输出不同的行。你知道吗

相关问题 更多 >