Specifying formatting for csv.writer in Python

I use csv.DictWriter to output csv files from a set of dictionaries. I am using 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 field names are headers that should be serialized to a file.

Some of the values ​​in my list of dictionaries (dirows) are numeric - for example. float, and I would like to indicate their formatting. For example, I would like the floats to be serialized with "% .2f" rather than full precision. Ideally, I would like to point out some kind of mapping that says how to format each type, for example.

 {float: "%.2f"} 

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

How can I do that?

The only other solution I can think of is: instead of messing with DictWriter formatting, just use the decimal package to specify the decimal precision of the float as% .2, which will result in serialization as such. Not sure if this is the best solution?

Many thanks for your help.

+4
source share
1 answer
 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.

+5
source

Source: https://habr.com/ru/post/1311981/


All Articles