Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a csv with a comma as the 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 csv module)

like image 536
maniexx Avatar asked Oct 03 '16 14:10

maniexx


Video Answer


1 Answers

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:
    writer.writerow(localize_floats(row))

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

like image 83
skovorodkin Avatar answered Sep 24 '22 01:09

skovorodkin