在Python中指定csv.writer的格式 [英] Specifying formatting for csv.writer in Python

查看:1458
本文介绍了在Python中指定csv.writer的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用csv.DictWriter从一组字典输出csv文件。我使用以下函数:

I am using csv.DictWriter to output csv files from a set of dictionaries. I use the following function:

def dictlist2file(dictrows, filename, fieldnames, delimiter='\t',
          lineterminator='\n'):
    out_f = open(filename, 'w')

    # Write out header
    header = delimiter.join(fieldnames) + lineterminator
    out_f.write(header)

    # Write out dictionary
    data = csv.DictWriter(out_f, fieldnames,
              delimiter=delimiter,
              lineterminator=lineterminator)
    data.writerows(dictrows)
    out_f.close()

我的字典列表(dictrows)中的一些值是数字的,它们都是字典列表,例如浮动,我想指定这些的格式。例如,我可能想要使用%.2f序列化浮点数,而不是全精度。理想情况下,我想指定某种类型的映射,说明如何格式化每种类型,例如。

Some of the values in my dictionary list (dictrows) are numeric -- e.g. floats, and I'd like to specify the formatting of these. For example, I might want floats to be serialized with "%.2f" rather than full precision. Ideally, I'd like to specify some kind of mapping that says how to format each type, e.g.

{float: "%.2f"}

表示如果你看到一个浮动,用%.2f格式化。有没有一个简单的方法来做到这一点?我不想子类化DictWriter或任何复杂的东西 - 这似乎是非常通用的功能。

that says that if you see a float, format it with %.2f. Is there an easy way to do this? I don't want to subclass DictWriter or anything complicated like that -- this seems like very generic functionality.

如何这样做?

我可以想到的唯一的另一个解决方案是,而不是搞乱DictWriter的格式化,只是使用十进制包来指定浮点的十进制精度为%.2,这将导致序列化因此。不知道这是否是更好的解决方案?

The only other solution I can think of is: instead of messing with the formatting of DictWriter, just use the decimal package to specify the decimal precision of floats to be %.2 which will cause to be serialized as such. Don't know if this is a better solution?

非常感谢您的帮助。

推荐答案

class TypedWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which uses "fieldformats" to format fields.
    """

    def __init__(self, f, fieldnames, fieldformats, **kwds):
        self.writer = csv.DictWriter(f, fieldnames, **kwds)
        self.formats = fieldformats

    def writerow(self, row):
        self.writer.writerow(dict((k, self.formats[k] % v) 
                                  for k, v in row.iteritems()))

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

未测试。

这篇关于在Python中指定csv.writer的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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