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.
精彩评论