首页 > 解决方案 > 在读取和执行操作时写入 CSV 文件时未写入数据

问题描述

我试图在对从另一个 csv 文件读取的数据进行操作时写入文件,但问题是内容没有被写入文件。这是我的代码片段。任何帮助是极大的赞赏。我正在阅读的 csv 文件看起来像这样。

CustID CustName PrincipleAmount NumberOfYears DepositType FinalAmount

1 Aaa 100,000 2 储蓄
2 Bbb 5,000 5 固定
3 Ccc 8,200 4 储蓄
4 Ddd 15,000 10 固定
5 Eee 6,500 20 固定

    from os import path
    my_path = 'C:\\JupyterNotebook\\'
    with open(path.join(my_path, 'Deposit.csv'), 'r+') as open_file, open(path.join(my_path, 
    'Deposit2.csv'), 'w+') as write_file:
        table = open_file.read()
        #headers = next(rows,None)
        rows =  table.split('\n')
        headers = str(rows.pop(0))

        to_write  = headers 
        write_file.write(to_write)
        result =[]
        for row in rows:
            if(len(row) == 0):   
                continue
            content = list(filter(lambda x: x not in ("", " "), row.split(',')))
            principal, years, deposit_Type = float(content[2]), float(content[3]), content[4]
            Amount = final_Amount(principal, years, deposit_Type)
            to_write = "%s, %s, %s,%s, %s, %s" % (content[0], content[1], content[2], content[3], content[4], Amount)
            write_file.write(to_write)

        print(write_file.read())

标签: pythoncsv

解决方案


推荐阅读