maniexx maniexx - 4 months ago 47
Python Question

How to write a csv with a comma as decimal separator?

I am trying to create a european-formatted csv in python. I already set the separator to a semicolon

writer = csv.writer(response, delimiter=';', quoting=csv.QUOTE_ALL)

However, this still uses dot
as the decimal separator. What's the correct way to make it use a comma, as is correct for my locale?
I can't seem to find any way to set it in the docs. (I am using, and would prefer to stick to, the built-in

This got marked as a duplicate, but the linked question concerns reading and not writing. I could not find an answer concerning writing. And those subjects are (slightly, but importantly) different.


A little bit hacky way, but it's the best I can think of: convert floats to strings and replace . with ,:

def localize_floats(row):
    return [
        str(el).replace('.', ',') if isinstance(el, float) else el 
        for el in row

for row in rows:

If you want better localization handling, I suggest you to convert all numbers using babel.numbers package.