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

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

问题描述

我想将像 [1,2,'a','He said "what what 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.

我目前的解决方案是这个有点hacky的函数:

My current solution is this somewhat hacky function:

def CSV_String_Writeline(data):
    class Dummy_Writer:
        def write(self,instring):
            self.outstring = instring.strip("
")
    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?

这是我最终的做法:

def csv2string(data):
    si = StringIO.StringIO()
    cw = csv.writer(si)
    cw.writerow(data)
    return si.getvalue().strip('
')

推荐答案

你可以使用 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 类的更快版本.

There is also cStringIO, which is a faster version of the StringIO class.

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

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