formatting number in the CSV module

Peter Otten __peter__ at web.de
Fri Sep 12 07:40:33 EDT 2003


Sebastien de Menten wrote:

> Hi,
> 
> I need to output numbers to a csv file and use the new csv module in
> python2.3:
> 
> "
> import csv
> data = [[ 0.321524523,0.5243523],[0.54635643,0.62776]]
> w = csv.writer(file("out.csv","w"))
> w.writerows(data)
> "
> 
> However, I would like to format the number so that only the first 2
> decimals are stored in the csv file.
> 
> Is it possible to specify a formatting command like "%.2f" to the csv
> writer ?
> 

I suggest wrapping your data into a generator:

import csv
import sys
data = [
    [ 0.321524523,0.5243523],
    [0.54635643,0.62776]
]

def formatdata(data):
    for row in data:
        yield ["%0.2f" % v for v in row]

w = csv.writer(sys.stdout)
w.writerows(formatdata(data))

Peter




More information about the Python-list mailing list