formatting number in the CSV module
Skip Montanaro
skip at pobox.com
Fri Sep 12 16:36:48 EDT 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
0.32,0.52
0.55,0.63
Skip
More information about the Python-list
mailing list