在i上读取和执行操作时写入CSV文件时未写入数据

2024-04-25 12:06:06 发布

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

我试图在对从另一个csv文件读取的数据执行操作时写入文件,但问题是内容没有写入文件。这是我的代码片段。非常感谢您的帮助。 我正在读取的csv文件如下所示

CustID CustName PrincipleAmount NumberOfYears存款类型FinalAmount

1 Aaa 100000 2节省
2 Bbb 5000 5固定电话
3 Ccc 8200 4保存
4 Ddd 15000 10固定的
5 Eee 6500 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())

Tags: 文件csvtopathmyasopencontent