基于地区设置的Python CSV列表分隔符

2024-10-01 09:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我发现Excel从“Regional Options->;Numbers->;List separator”中使用CSV元素分隔符。Python中的locale模块用于检测区域性设置,但是(locale.localeconv)不包含列表分隔符。用dialect='excel'打开CSV writer没有帮助。你知道怎么找到正确的分离器吗?在

编辑

下面的代码似乎有效(但不能接受任何赞成票,因为解决方案不是我的)

import locale

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

Tags: 文件csv用户gt机器列表excellocale
3条回答

我使用sniff自动检测它:

import csv

dialect = csv.Sniffer().sniff(file.readline())
file.seek(0)
file.readline()
file.seek(0)
fieldnames=( 'assignatura', 'professor', 'grup',  )
reader = csv.DictReader(file, fieldnames=fieldnames, dialect=dialect )

for row in reader:

        codiFranja = unicode(row['assignatura'],'iso-8859-1')
        ...

编辑:

如果您计划从python创建csv并从excel读取它,那么您需要使用locale分隔符创建文件。但是python csv模块不使用locale:http://mail.python.org/pipermail/csv/2003-May/000507.html

Andreas> This could be really simple to implement using the locale module. But I took a short look at the locale module and it seems like there is no way to get the list separator sign (probably it's not POSIX complaint).

一种解决方法可能是在每个python用户客户端安装上基于locale桌面计算机的配置文件上写入分隔符,并在python生成csv文件时读取此分隔符。在

您还可以编写vbscript代码来创建excel文件并将其导出到csv,然后在每次需要创建python csv文件时查找分隔符。在

也许最优雅的解决方案是使用架构.ini:http://msdn.microsoft.com/en-us/library/windows/desktop/ms709353(v=vs.85).aspx。您可以生成csv文件,并在同一文件夹中,架构.ini文件。在

xlwt编写XLS文件。在

取2:使用语言环境模块和一些启发式方法:

>>> 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)
',' ';'
>>>

提供了从Windows注册表读取列表分隔符符号的思想。在

提供了访问Windows注册表值的代码。在

使用_winreg package,可以从注册表检索Windows列表分隔符值,如下所示:

from _winreg import *

def getListSeparator():
    '''Retrieves the Windows list separator character from the registry'''
    aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
    aKey = OpenKey(aReg, r"Control Panel\International")
    val = QueryValueEx(aKey, "sList")[0]
    return val

print getListSeparator()

相关问题 更多 >