How to write a csv with a comma as the decimal separator?
17,224
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.
Related videos on Youtube
Comments
-
maniexx over 1 year
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-incsv
module)-
martineau over 7 years@maniexx: Yes, the other question is about reading and yours is about writing. However that is a minor difference, since the solution in either case is to replace the decimal mark character with something else,
'.'
with','
or vice-versa in the duplicate. The answers to the other question are slightly better, IMO, because they also deal with potential issues when dealing with large numbers with a mixture of the two character in them, as well as describing code that does things in a locale-aware way. -
Basj over 5 yearsAs stated by OP, this got marked as a duplicate, but the linked question concerns reading and not writing.
-
Michel de Ruiter over 4 yearsAlthough the solution might be similar, the question is not a duplicate!
-
Ali SAID OMARWhat the about the decimal separator from the data source ?
-
-
maniexx over 7 yearsWon't they be encoded as strings in the csv? IE quoted and interpreted as strings by other software?
-
skovorodkin over 7 yearsThey won't be quoted as you set
;
as delimiter. -
skovorodkin over 7 yearsI don't know how other software will handle such format though. IMO it's easier to output numbers as is and then localize them when you really need that (e.g. in UI).
-
maniexx over 7 yearsYeah, but the csv is going to be read in excel and such. So that's sadly not an option. And an XLS(x) or some other format which is actually a format is not allowed either.
-
skovorodkin over 7 yearsGot it. Then just replace dots with commas or use Babel's
format_number
function. It'll work. -
maniexx over 7 yearsI tested your answer, it works for me. Thanks a lot, and I'll be sure to checkout babel if it turns out I need localization somewhere else. (Right now django handles it for me in most places, so I don't want to add it just for this one minor functionality)