我需要使用Python将包含逗号的字符串添加到CSV文件中。有人说用双引号将字符串引起来可以避免逗号之间的逗号。这是行不通的。如何在不将逗号识别为分隔符的情况下编写此字符串?
string = "WORD;WORD 45,90;WORD 45,90;END;"
with open('doc.csv') as f:
prepended = string + '\n' + f.read()
with open('doc.csv', 'w') as f:
f.write(prepended)
答案 0 :(得分:1)
因此,正如您所指出的,通常可以如下所示引用字符串。读取这些文件的系统是否无法识别该语法?如果您使用python的csv
模块,它将处理正确的转义:
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(myIterable, quoting=csv.QUOTE_ALL)
加引号的字符串如下:
"string1","string 2, with, commas"
请注意,如果字符串中包含引号字符,则将其写为""
(连续两个引号字符):
"string1","string 2, with, commas, and "" a quote"