import csv
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["SN", "Name", "Contribution"])
writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
The output I get:
SN, Name, Contribution
1, Linus Torvalds, Linux Kernel
The output I want:
SN, Name, Contribution
1, Linus Torvalds, "Linux Kernel"
So, I tried
writer.writerow([1, "Linus Torvalds", "\"Linux Kernel\""])
But that just makes it into:
1, Linus Torvalds, ""Linux Kernel""
I'm using Visual Studio Code with python 3, not sure how I can get it to output the word with double quotes
You can control the level of quoting with quoting argument to csv.writer. If you just want to quote all values, use csv.QUOTE_ALL.
Quoting levels:
csv.QUOTE_ALL
Instructs writer objects to quote all fields.
csv.QUOTE_NONNUMERIC
Instructs writer objects to quote all non-numeric fields.
Instructs the reader to convert all non-quoted fields to type float.
csv.QUOTE_MINIMAL (Default)
Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.
csv.QUOTE_NONE
Instructs writer objects to never quote fields.
Example:
import csv
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(["SN", "Name", "Contribution"])
writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
Output:
"SN","Name","Contribution"
1,"Linus Torvalds","Linux Kernel"
Notice in the output that all the strings are quoted and the number is not.
If use quoting=csv.QUOTE_MINIMAL then output is the following. None of the strings have new line or escape characters so no quotes are required.
SN,Name,Contribution
1,Linus Torvalds,Linux Kernel
import csv
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file,quotechar = "'")
writer.writerow(["SN", "Name", "Contribution"])
writer.writerow([1, "Linus Torvalds",'"Linux Kernel"' ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With