简体   繁体   中英

Csv write Double quotes

I was creating a CSV from python's CSV writer, where I want the same data as the input CSV but some texts with double-quotes. I have successfully added the text I wanted but I'm struggling with double quotes in the text. The output file is giving me 3 double quotes instead of just 1. Here is my code until now:

with open('test.txt',newline='') as f:
    r = csv.reader(f,delimiter='\t')
    data = [line for line in r]

with open('abc.csv','w',newline='') as f:
    w = csv.writer(f, delimiter=',')
    w.writerow(["some of my text"])
    w.writerow(["some more: 123456"])
    w.writerow(["even more: 5555"])
    w.writerow([f"with a variable: {time}"])
    w.writerows(data)

the output of the inserted text of this code is like this:

"""some of my text"""

"""some more: 123456"""

"""even more: 5555"""

"""with a variable: 28th oct"""

Please suggest where am I missing to remove these triple quotes.

3 double quotes instead of just 1

That is correct. In CSV, the " is used to surround values containing special characters. In order to include a literal " it must be escaped by doubling it.

So you get one " for the start/end of the value, and then two "" to encode the quote in the value.

RFC 4180 §2 ¶7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM