python csv列表分隔符基于区域设置 [英] python csv list separator based on regional settings

查看:179
本文介绍了python csv列表分隔符基于区域设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在使用Python的用户计算机中检测列表分隔符?

how to detect list separator in users machine with Python?

需要在用户计算机上创建CSV文件,并且必须自动检测列表分隔符可以读取CSV文件)。

CSV file needs to be created on users machine and the list separator must be detected automatically (so that excel can read the CSV file).

我发现Excel从区域选项 - >数字 - >列表分隔符中选取CSV元素分隔符。 Python中的locale模块用于检测文化设置,但它(locale.localeconv)不包含列表分隔符。使用dialect ='excel'打开CSV写入程序没有帮助。任何想法如何获得正确的分隔符?

I've found out that Excel takes CSV elements separator from "Regional Options -> Numbers -> List separator". locale module in Python is used to detect cultural settings, but it (locale.localeconv) does not contain list separator. Opening CSV writer with dialect='excel' does not help. Any idea how to get the correct separator?

EDIT

似乎工作(但不能接受任何upvote,因为解决方案不是我的)

The following code seems to work (but can't accept any upvotes as the solution is not mine)

import locale

langlocale = locale.getdefaultlocale()[0]
locale.setlocale(locale.LC_ALL, langlocale)
dp = locale.localeconv()['decimal_point']
delimiter = ','
if dp == ',':
    delimiter = ';'


推荐答案

使用 xlwt 编写XLS文件。

Take 2:使用区域设置模块和一些启发式方法:

Take 2: Use the locale module and some heuristics:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '') # set to user's locale, not "C"
'English_Australia.1252'
>>> dec_pt_chr = locale.localeconv()['decimal_point']
>>> if dec_pt_chr == ",":
...     list_delimiter = ";"
... else:
...     list_delimiter = ","
...
>>> print repr(dec_pt_chr), repr(list_delimiter)
'.' ','
>>> locale.setlocale(locale.LC_ALL, 'French_France.1252')
'French_France.1252'
>>> dec_pt_chr = locale.localeconv()['decimal_point']
>>> if dec_pt_chr == ",":
...     list_delimiter = ";"
... else:
...     list_delimiter = ","
...
>>> print repr(dec_pt_chr), repr(list_delimiter)
',' ';'
>>>

这篇关于python csv列表分隔符基于区域设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆