[英]How to write a csv with a comma as the decimal separator?
I am trying to create a european-formatted csv in python.我正在尝试在 python 中创建一个欧洲格式的 csv。 I already set the separator to a semicolon我已经将分隔符设置为分号
writer = csv.writer(response, delimiter=';', quoting=csv.QUOTE_ALL)
However, this still uses dot .
但是,这仍然使用 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) (我正在使用并且更愿意坚持使用内置的csv
模块)
A little bit hacky way, but it's the best I can think of: convert floats to strings and replace .
有点hacky的方式,但这是我能想到的最好的方法:将浮点数转换为字符串并替换.
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.如果您想要更好的本地化处理,我建议您使用babel.numbers
包转换所有数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.