Search code examples
pythoncsvexport-to-csv

I need to edit a python script to remove quotes from a csv, then write back to that same csv file, quotes removed


I have seen similar posts to this but they all seem to be print statements (viewing the cleaned data) rather than overwriting the original csv with the cleaned data so I am stuck. When I tried to write back to the csv myself, it just deleted everything in the file. Here is the format of the csv:

30;"unemployed";"married";"primary";"no";1787;"no";"no";"cellular";19;"oct";79;1;-1;0;"unknown";"no"
33;"services";"married";"secondary";"no";4747;"yes";"cellular";11;"may";110;1;339;2;"failure";"no"
35;"management";"single";"tertiary";"no";1470;"yes";"no";"cellular";12;"apr"185;1;330;1;"failure";"no"

It is delimited by semicolons, which is fine, but all text is wrapped in quotes and I only want to remove the quotes and write back to the file. Here is the code I reverted back to that successfully reads the file, removes all quotes, and then prints the results:

import csv
f = open("bank.csv", 'r')
try:
    for row in csv.reader(f, delimiter=';', skipinitialspace=True):
        print(' '.join(row))
finally:
        f.close()

Any help on properly writing back to the csv would be appreciated, thanks!


Solution

  • You could do something like this. Read it in, and write using quoting=csv.QUOTE_NONE

    import csv
    f = open("bank.csv", 'r')
    inputCSV = []
    try:
        for row in csv.reader(f, delimiter=';', skipinitialspace=True):
            inputCSV.append(row)
    finally:
            f.close()
    
    with open('bank.csv', 'w', newline='') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=';')
        for row in inputCSV:
            csvwriter.writerow(row)