Dibble
Dibble

Reputation: 31

Adding double quotes while making a csv file in python

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

Upvotes: 2

Views: 5501

Answers (2)

CodeMonkey
CodeMonkey

Reputation: 23748

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

Upvotes: 7

Sihab Sahariar
Sihab Sahariar

Reputation: 41

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

Upvotes: 1

Related Questions