Kristian
Kristian

Reputation: 11

(Basic) Python CSV Import, Replace, Export

Hoping for someone to help me out with something to help with personal finance.

I use an online budget tool but my bank statements are formatted annoyingly.

Trying to script a CSV modification that reads a file, and replaces part of a string in the second column (12 characters removed from start if "Visa Purchase" exists in string, then dumps it out as a renamed CSV.

Any help would be much appreciated.

so far I have the below (to read file and give options for displaying);

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

Thanks!

Upvotes: 0

Views: 49

Answers (1)

Arun
Arun

Reputation: 2003

I think you are looking for python string slicing:

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

Please let me know whether it was helpful.

Upvotes: 1

Related Questions