xtheking
xtheking

Reputation: 564

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

Upvotes: 1

Views: 2972

Answers (4)

mohd4482
mohd4482

Reputation: 1918

According to RFC 4180: "If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote."

But if you want to change that based on your specific need, try to disable double quoting and you must define an escape character:

import csv

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

the output file will be like:

"hello, my name is \"Joe\""

However, I recommend using the quotechar parameter of csv.writer to change the quote character as in the other answer by @AndrejKesely.

Upvotes: 4

Ammar
Ammar

Reputation: 40

Two solutions:

Either you can use quotechar for changing the quote character so that it ignores the double quotes found in string. csv.writer(f_out, quotechar="'") will do for your case.

Or you can set escapechar="\\" along with the doublequote=False. That will put backslash before every double quote for escaping it in the string. csv.writer(f_out, escapechar="\\", doublequote=False)

Try both of these. I hope this will answer your question.

Upvotes: 0

barker
barker

Reputation: 1055

import csv

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

Upvotes: -2

Andrej Kesely
Andrej Kesely

Reputation: 195418

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

Upvotes: 6

Related Questions