如何将数据作为字符串(而非文件)写入CSV格式? [英] How do I write data into CSV format as string (not file)?

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

问题描述

我想将像[1,2,'a','He said "what do you mean?"']这样的数据转换为CSV格式的字符串.

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?

这是我最终完成的方式:

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类的更快版本.

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

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