根据我之前的问题,如何将字符串列表加入到字符串中,以便干净地引用值.就像是:
['a', 'one "two" three', 'foo, bar', """both"'"""]
成:
a, 'one "two" three', "foo, bar", "both\"'"
我怀疑csv模块将在这里发挥作用,但我不知道如何获得我想要的输出.
使用该csv
模块,您可以这样做:
import csv writer = csv.writer(open("some.csv", "wb")) writer.writerow(the_list)
如果您需要一个字符串,只需使用StringIO
实例作为文件:
f = StringIO.StringIO() writer = csv.writer(f) writer.writerow(the_list) print f.getvalue()
输出: a,"one ""two"" three","foo, bar","both""'"
csv
将以稍后可以回读的方式书写.您可以通过定义一个微调其输出dialect
,只需设置quotechar
,escapechar
等等,需要:
class SomeDialect(csv.excel): delimiter = ',' quotechar = '"' escapechar = "\\" doublequote = False lineterminator = '\n' quoting = csv.QUOTE_MINIMAL f = cStringIO.StringIO() writer = csv.writer(f, dialect=SomeDialect) writer.writerow(the_list) print f.getvalue()
输出: a,one \"two\" three,"foo, bar",both\"'
相同的方言可以与csv模块一起使用,以便稍后将字符串读回列表.