title: Specifying formatting for csv.writer in Python
body: <p>I am using csv.DictWriter to output csv files from a set of dictionaries.  I use the following function:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>where dictrows is a list of dictionaries, and fieldnames provides the headers that should be serialized to file.</p>
  
  <p>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. </p>
  
  <pre><code>{float: "%.2f"}
  </code></pre>
  
  <p>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.</p>
  
  <p>How can this be done?</p>
  
  <p>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?</p>
  
  <p>thanks very much for your help.</p>