问题描述
我想将一个csv格式化的字符串数据转换为 [1,2,'a','他说'你是什么意思?'']
I want to cast data like [1,2,'a','He said "what do you mean?"']
to a csv-formatted string.
通常会使用 csv.writer()
来处理所有疯狂的边缘转义,引用标记转义,CSV方言等)捕获是 csv.writer()
期望输出到文件对象,而不是字符串。
Normally one would use csv.writer()
for this, because it handles all the crazy edge cases (comma escaping, quote mark escaping, CSV dialects, etc.) The catch is that csv.writer()
expects to output to a file object, not to a string.
我现在的解决方案是这个有点黑客的函数:
My current solution is this somewhat hacky function:
def CSV_String_Writeline(data):
class Dummy_Writer:
def write(self,instring):
self.outstring = instring.strip("\r\n")
dw = Dummy_Writer()
csv_w = csv.writer( dw )
csv_w.writerow(data)
return dw.outstring
任何人都可以给出一个更优雅的解决方案,仍然可以处理边缘情况?
Can anyone give a more elegant solution that still handles the edge cases well?
编辑:这是我最后做的: / p>
Here's how I ended up doing it:
def csv2string(data):
si = StringIO.StringIO()
cw = csv.writer(si)
cw.writerow(data)
return si.getvalue().strip('\r\n')
推荐答案
您可以使用,而不是您自己的 Dummy_Writer
:
还有,这是 StringIO
类。
这篇关于Python - 将数据写入csv格式为字符串(不是文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!