nathanm nathanm - 2 months ago 25
Python Question

Remove double quotes from csv row

I have two files: src.csv and dst.csv. The code below reads the second row from src.csv and appends it to dst.csv. The issue is the output in dst.csv is contained within double quotes ("").

Expected result:

10, 5, 5, 10, 1


Output:

"10, 5, 5, 10, 1"


I have tried using
quoting=csv.QUOTE_NONE, escapechar=' '
in csv.writer and it does remove the quotes though the output now contains a blank space after each csv value.

Here is my code:

import csv

with open('src.csv', 'r') as src, open('dst.csv', 'a', newline='') as dst:
wr = csv.writer(dst, dialect='excel', delimiter=',', quoting=csv.QUOTE_NONE, escapechar=' ')
next(src)
for row in src:
wr.writerow([row.rstrip('\n')])


Any suggestions?

Answer

You don't split the source file rows into columns so you just ended up writing a 1 column csv. Use a reader instead:

import csv

with open('src.csv', 'r') as src, open('dst.csv', 'a', newline='') as dst:
    wr = csv.writer(dst, dialect='excel', delimiter=',', quoting=csv.QUOTE_NONE, escapechar=' ')
    next(src)
    reader = csv.reader(src)
    for row in reader:
        wr.writerow(row)