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
CodePudding user response:
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.
CodePudding user response:
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"' ])