Specifying formatting for csv.writer in Python
- by user248237
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.