python csv writer_在Python中指定csv.writer的格式

1586010002-jmsa.png

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()

where dictrows is a list of dictionaries, and fieldnames provides the headers that should be serialized to file.

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"}

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.

How can this be done?

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?

thanks very much for your help.

解决方案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)

Not tested.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值