(基本)Python CSV导入,替换,导出

时间:2017-11-10 09:58:57

标签: python python-3.x csv

希望有人帮我解决个人理财问题。

我使用的是在线预算工具,但我的银行对帐单格式很烦人。

  

尝试编写一个读取文件并替换的CSV修改脚本   第二列中字符串的一部分(从中移除12个字符)   如果"签证购买"存在于字符串中,然后将其转储为   重命名为CSV。

非常感谢任何帮助。

到目前为止,我有以下内容(阅读文件并提供显示选项);

csvfile = input("CSV File Name?: ")
choice = input("all or some?: ")

import csv

with open(csvfile + '.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

    if choice == "all":
        for row in readCSV:
            print(row)

    elif choice == "some":
        for row in readCSV:
            print(row[0], row[1])

    else:
        print("Error")

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找python字符串切片:

import csv

csvfile = input("CSV File Name?: ")
choice = input("all or some?: ")

with open(csvfile+'.csv') as csvfile, open('output.csv', 'w', encoding='utf-8') as outfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    writer = csv.writer(outfile, lineterminator='\n', quoting=csv.QUOTE_ALL)
    if choice =="all": 
        for row in readCSV:
            writer.writerow(row)
    elif choice =="some": 
        for row in readCSV:
            text = row[1]
            if text.startswith('Visa Purchase'):
                text = row[14:]
            writer.writerow(row[0], text)
    else:
        print("Error")

请告诉我这是否有帮助。