Python - 将数据写入csv格式为字符串(不是文件) [英] Python - write data into csv format as string (not file)

查看:821
本文介绍了Python - 将数据写入csv格式为字符串(不是文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个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')


推荐答案

您可以使用 StringIO ,而不是您自己的 Dummy_Writer


此模块实现一个类文件类, StringIO ,读取和写入字符串缓冲区内存文件)。

This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).

还有 cStringIO ,这是 StringIO 类。

这篇关于Python - 将数据写入csv格式为字符串(不是文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆