Save list to csv with two decimal digits in python?

marc picture marc · Oct 7, 2013 · Viewed 11.1k times · Source

I have data which looks like

[('A',5.3748),('B',8.324203),('C',3.492)]

I'm saving it to a csv with the following lines:

with open('output.csv','wb') as fp:
    a = csv.writer(fp,delimiter = ",")
    a.writerows(data)

Works like a charm except that I would like to display my values with only two decimal digits. Earlier in my code I zip two lists to get the data. So I could make the change before if need be.

Thanks!

Answer

Martin Richard picture Martin Richard · Oct 7, 2013

You can use the string formatting syntax:

with open('output.csv','wb') as fp:
    a = csv.writer(fp,delimiter = ",")
    a.writerows(map(lambda t: (t[0], "%.2f" % t[1]), data))

The trick is here:

>> "%.2f" % a_number

will print the number with two decimal digits, while

map(lambda t: (t[0], "%.2f" % t[1]), data)

will apply this transformation to every tuples in the list data. (see http://docs.python.org/2/library/functions.html#map)