Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Writing quotes around strings to CSVs in Python

I was following the guide here to learn about writing to CSV files. https://teamtreehouse.com/library/csv-and-json-in-python

I grabbed an example CSV file from the internet and it is as follows:

"Name","Sex","Age","Height (in)","Weight (lbs)"
"Alex","M",41,74,170
"Bert","M",42,68,166
"Carl","M",32,70,155
"Dave","M",39,72,167

After following the guide, I am able to write to the file using the following code:

def write():
    with open("stats.csv", "a") as file:
        fieldnames = ["Name","Sex","Age","Height (in)","Weight (lbs)"]
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writerow({
            "Name": "Bill",
            "Sex": "M",
            "Age": 19,
            "Height (in)": 102,
            "Weight (lbs)": 234
        })
    pass

if __name__ == "__main__":
    #read()
    write()

However, my output now looks like this:

"Name","Sex","Age","Height (in)","Weight (lbs)"
"Alex","M",41,74,170
"Bert","M",42,68,166
"Carl","M",32,70,155
"Dave","M",39,72,167
Bill,M,19,102,234

I want to make sure my code writes the quotes around the strings. I figured out this way works, but I can't understand why:

def write():
    with open("stats.csv", "a") as file:
        fieldnames = ["Name","Sex","Age","Height (in)","Weight (lbs)"]
        writer = csv.DictWriter(file, fieldnames=fieldnames, quotechar=" ")
        writer.writerow({
            "Name": "\"Bill\"",
            "Sex": "\"M\"",
            "Age": 18,
            "Height (in)": 102,
            "Weight (lbs)": 234
        })
    pass

if __name__ == "__main__":
    #read()
    write()

After researching the quotechar parameter, it is still unclear to my why a "space" would work here. Without this quotechar parameter, my output looks like this. Using double quotes as '" string "' also does the same weird tripple quote thing:

"Name","Sex","Age","Height (in)","Weight (lbs)"
"Alex","M",41,74,170
"Bert","M",42,68,166
"Carl","M",32,70,155
"Dave","M",39,72,167

"Bill","M",18,102,234

"""Bill""","""M""",18,102,234

So if anyone can offer some advice or insight into this behavior that would be great. Also, it keeps creating a new line every time I run it. If you also have any idea about that it would be great. Thank you!

I have resolved the issue by using the following code:

import csv

dictionary = [{"Name":"Alex","Sex":"M","Age":41,"Height (in)":74,"Weight (lbs)":170},
        {"Name":"Bert","Sex":"M","Age":41,"Height (in)":74,"Weight (lbs)":170},
        {"Name":"Card","Sex":"M","Age":41,"Height (in)":74,"Weight (lbs)":170},
        {"Name":"Dave","Sex":"M","Age":41,"Height (in)":74,"Weight (lbs)":170}]


def write():
    with open("stats.csv", "a") as file:
        fieldnames = ["Name","Sex","Age","Height (in)","Weight (lbs)"]
        writer = csv.DictWriter(file, delimiter=",", fieldnames=fieldnames, quoting=csv.QUOTE_STRINGS, lineterminator="\n")
        for line in dictionary:   
             #print(line["Name"]) 
            writer.writerow(line)      
write()  

Output is as follows:

"Name","Sex","Age","Height (in)","Weight (lbs)"
"Alex","M",41,74,170
"Bert","M",42,68,166
"Carl","M",32,70,155
"Dave","M",39,72,167
"Alex","M",41,74,170
"Bert","M",41,74,170
"Alex","M",41,74,170
"Bert","M",41,74,170
"Card","M",41,74,170
"Dave","M",41,74,170

The key changes were adding the quoting=csv.QUOTE_STRINGS and lineterminator="\n" parameters to the CSV DictWriter.

However, I am still intersted to learn why this example from my first post worked. Specifically, why quotechar=" " and "\" string \"" worked together to product the desired output.

def write():
    with open("stats.csv", "a") as file:
        fieldnames = ["Name","Sex","Age","Height (in)","Weight (lbs)"]
        writer = csv.DictWriter(file, fieldnames=fieldnames, quotechar=" ")
        writer.writerow({
            "Name": "\"Bill\"",
            "Sex": "\"M\"",
            "Age": 18,
            "Height (in)": 102,
            "Weight (lbs)": 234
        })
    pass

if __name__ == "__main__":
    #read()
    write()

If you have any insight please let me know!

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

I am glad you solved your problem. You might want to consult the documentation regarding the csv reader/writer packages. This would help you write it a bit more efficiently.

For example you might have chosen to take advantage of the writer.writeheader() function which would have saved you a little bit of typing.

Also... probably want to look into quotechar and delimiter which would allow you to get around any possible confusion in the code.

https://docs.python.org/3/library/csv.html