formatting number in the CSV module

Skip Montanaro skip at
Fri Sep 12 22:36:48 CEST 2003

    Sebastien> I need to output numbers to a csv file and use the new csv
    Sebastien> module in python2.3:

    Sebastien> "
    Sebastien> import csv
    Sebastien> data = [[ 0.321524523,0.5243523],[0.54635643,0.62776]]
    Sebastien> w = csv.writer(file("out.csv","w"))
    Sebastien> w.writerows(data)
    Sebastien> "

    Sebastien> However, I would like to format the number so that only the
    Sebastien> first 2 decimals are stored in the csv file.

There's nothing built into the csv module.  You can format the floats before
passing them to the writer however:

    >>> import csv
    >>> data = [[ 0.321524523,0.5243523],[0.54635643,0.62776]]
    >>> w = csv.writer(file("out.csv","w"))
    >>> for row in data:
    ...     row = ["%.2f"%f for f in row]
    ...     w.writerow(row)
    montanaro:tmp% cat out.csv


More information about the Python-list mailing list