[英]Specifying formatting for csv.writer in Python
I am using csv.DictWriter to output csv files from a set of dictionaries. 我正在使用csv.DictWriter从一组字典输出csv文件。 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. 其中dictrows是一个字典列表,而fieldnames提供了应序列化为文件的标题。
Some of the values in my dictionary list (dictrows) are numeric -- eg floats, and I'd like to specify the formatting of these. 我的字典列表(dictrows)中的一些值是数字 - 例如浮点数,我想指定这些值的格式。 For example, I might want floats to be serialized with "%.2f" rather than full precision.
例如,我可能希望使用“%。2f”而不是完全精度序列化浮点数。 Ideally, I'd like to specify some kind of mapping that says how to format each type, eg
理想情况下,我想指定某种映射,说明如何格式化每种类型,例如
{float: "%.2f"}
that says that if you see a float, format it with %.2f. 如果你看到浮动,请用%.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或类似的任何复杂的子类化 - 这似乎是非常通用的功能。
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. 我能想到的唯一其他解决方案是:不要乱用DictWriter的格式,只需使用十进制包将浮点数的小数精度指定为%.2,这将导致序列化。 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. 没有测试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.