问题描述
免责声明:我在欧洲。
根据 Excel使用分号; 作为欧洲的默认分隔符,以用十进制逗号防止冲突。
According to this page Excel uses the semicolon ; as default separator in Europe to "prevent conflicts" with the decimal comma.
此Python代码:
import csv data = [["test", "data"], ["foo", "bar"]] writer = csv.writer(open("data.csv", "wb"), dialect="excel") writer.writerows(data)
应该生成此文件:
test;data foo;bar
它使用逗号。为什么会发生这种情况? locale.getdefaultlocale()返回('nl_NL','cp1252')。
but instead it uses commas. Why is this happening? locale.getdefaultlocale() returns ('nl_NL', 'cp1252').
推荐答案
这是因为csv.excel方言不是语言环境感知。如果您希望明确使用分号作为分隔符,则需要将分隔符显式传递给csv.open作为
This is because the csv.excel dialect is not locale aware. If you wish to explicitly use semicolons as the delimiter then you need to either explicitly pass the delimiter to csv.open as
writer = csv.writer(open("data.csv", "wb"), delimiter=";")
或创建一个新的方言并注册它
or create a new dialect and register it
class excel_semicolon(csv.excel): delimiter = ';' register_dialect("excel-semicolon", excel_semicolon)
测试浮点数的写法...我怀疑他们不会以你想要的欧洲格式书写(以逗号作为基数)
In either case, you should test how floating point numbers are written ... I suspect they won't be written in the European format you desire (with a comma as the radix)
这篇关于Python csv写错误分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!