Search code examples
pythoncsvdouble-quotesquoting

How to keep quotes in CSV-Files in Python?


Hello there,

I have a problem with correct quotes when writing a CSV. I want to write a CSV file with the built-in Python-CSV-library. My code is the following:

with open('test.csv', mode = 'w', newline = '') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter = ',', escapechar = '"', quoting = csv.QUOTE_NONE)

    csv_writer.writerow(['1', ' 0', ' Maker', ' "Tamas Nemes"'])
    csv_writer.writerow(['2', ' 0', ' Title', ' "A CSV file"'])

I tried many different parameter settings for the writer, but I always end up with this:

1, 0, Maker, ""Tamas Nemes""
2, 0, Title, ""A CSV file""

Is there a way to get it like this:

1, 0, Maker, "Tamas Nemes"
2, 0, Title, "A CSV file"

Thanks for your help in advance!


Solution

  • I'm not able to comment and I agree with @CharlesDuffy your kind of abusing the CSV format.

    But you can get close to what you want by setting Escape Character to space (" ")

    This will result in:

    1,  0,  Maker, "Tamas  Nemes "
    2,  0,  Title, "A  CSV  file "
    

    Your strings are padded with extra spaces, but depending on what you need to do with them that might not matter.