【发布时间】:2017-09-25 13:49:05
【问题描述】:
Python 3.1.3 我需要的是使用 ConfigParser 从 cp1251 文件中读取字典。 我的例子:
config = configparser.ConfigParser()
config.optionxform = str
config.read("file.cfg")
DataStrings = config.items("DATA")
DataBase = dict()
for Dstr in DataStrings:
str1 = Dstr[0]
str2 = Dstr[1]
DataBase[str1] = str2
之后,我尝试根据字典替换某些 UTF-8 文件中的一些单词。但有时它不起作用(例如,使用“新行回车”的符号)。 我的 UTF-8 文件和 CP1251 中的配置文件(字典)。似乎很麻烦,我必须将配置解码为 UTF-8。 我试过这个:
str1 = Dstr[0].encode('cp1251').decode('utf-8-sig')
但是出现了错误"'utf8' codec can't decode byte 0xcf in position 0"。
如果我使用.decode('','ignore') - 我几乎会丢失所有配置文件。
我该怎么办?
【问题讨论】:
-
config.read("file.cfg", encoding="cp1251") -
听起来不错,但不起作用。已经试过了。由于 Python3.x 没有“编码”属性。编码继承自 .open() 默认设置。
-
属性与什么有什么关系?
ConfigParser.read至少从 python 3.3 开始就有encoding关键字参数。我希望你没有使用旧版本。
标签: python dictionary encoding utf-8 configparser