Reputation: 518
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!
Upvotes: 2
Views: 1413
Reputation: 781004
What you're trying to create isn't standard CSV format. You can simply join all the strings and write that.
with open('test.csv', mode = 'w', newline = '') as csv_file:
csv_file.write(",".join(['1', ' 0', ' Maker', ' "Tamas Nemes"']) + "\n")
csv_file.write(",".join(['2', ' 0', ' Title', ' "A CSV file"']) + "\n")
Upvotes: 1
Reputation: 38
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.
Upvotes: 1