不要重新发明轮子,使用csv模块写出你的数据:
import csv
with open(outputfilename, 'wb') as outfh:
writer = csv.writer(outfh)
writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])
Run Code Online (Sandbox Code Playgroud)
您可以调整引用行为,但默认(Excel兼容)设置将为您处理逗号和嵌套引号的引用.引用包含引号或逗号的列,任何嵌入的引号加倍.
演示:
>>> from cStringIO import StringIO
>>> import csv
>>> out = StringIO()
>>> writer = csv.writer(out)
>>> writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])
>>> out.getvalue()
'"Data with , commas and nested "" quotes",works just fine\r\n'
Run Code Online (Sandbox Code Playgroud)