formatting number in the CSV module

  • Thread starter Sebastien de Menten
  • Start date
S

Sebastien de Menten

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 ?

Seb

ps: data in the real application is a BIG numeric array...
 
P

Peter Otten

Sebastien said:
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
 
S

Skip Montanaro

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,010
Latest member
MerrillEic

Latest Threads

Top