如何编写一个以逗号作为小数点分隔符的csv? [英] How to write a csv with a comma as the decimal separator?
问题描述
我正在尝试在python中创建欧洲格式的csv.我已经将分隔符设置为分号
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)
但是,它仍然使用点.
作为小数点分隔符.使它使用逗号的正确方法是什么(对我的语言环境而言是正确的)?
我似乎找不到在文档中设置它的任何方法. (我正在使用,并且希望坚持使用内置的csv
模块)
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)
推荐答案
有点笨拙,但这是我能想到的最好的方法:将浮点数转换为字符串并将.
替换为,
:
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))
如果您希望更好地进行本地化处理,建议您使用 babel.numbers
转换所有数字包.
If you want better localization handling, I suggest you convert all numbers using babel.numbers
package.
这篇关于如何编写一个以逗号作为小数点分隔符的csv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!