Search code examples
pythoncsvdelimiterquoting

CSV Writer Doubling Quotes


I have a string in Python: hello, my name is "Joe". When I try writing using the csv module, I get "hello, my name is ""Joe""". What I am hoping to see is "hello, my name is "Joe"".

Is there anyway to have the CSV writer not add double quotes when there are double quotes present?

code:

s = 'hello, my name is "Joe"'
with open(filename, 'w', newline='', encoding='utf-8') as f_out:
    writer = csv.writer(f_out)
    writer.writerow([s])

Solution

  • You can use quotechar parameter when you creating csv.writer (doc):

    import csv
    
    s = 'hello, my name is "Joe"'
    with open('out.csv', 'w', newline='', encoding='utf-8') as f_out:
        writer = csv.writer(f_out, quotechar="'")
        writer.writerow([s])
    

    Output of the file is:

    'hello, my name is "Joe"'