ConfigParser中的编码(Python)

问题描述:

Python 3.1.3 我需要的是使用ConfigParser从cp1251文件中读取字典。 我的例子:ConfigParser中的编码(Python)

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文件的一些话。但有时它不起作用(例如,带有“new line-carriage return”符号)。 我的UTF-8文件和CP1251的配置文件(字典)。似乎麻烦,我必须解码配置为UTF-8。 我tryed这一点:

str1 = Dstr[0].encode('cp1251').decode('utf-8-sig') 

但错误"'utf8' codec can't decode byte 0xcf in position 0"出现。 如果我使用.decode('','ignore') - 我只丢失了几乎所有的配置文件。 我该怎么办?

+1

'config.read(“file.cfg”,encoding =“cp1251”)' – Goyo

+0

听起来不错,不起作用。已经尝试过。由于Python3.x没有“编码”属性。编码从.open()默认设置继承。 –

+0

属性与什么有关? 'ConfigParser.read'至少从[python 3.3](https://docs.python.org/3.3/library/configparser.html#configparser.ConfigParser.read)有一个'encoding'关键字参数。我希望你没有使用旧版本。 – Goyo

Python 3.1在Python版本的无人地带。理想情况下,你会升级到Python 3.5,这将让你做config.read("file.cfg", encoding="cp1251")

如果你必须留在3.1X,您可以使用ConfigParser.readfp()方法使用正确的编码从先前打开的文件阅读:

import configparser 

config = configparser.ConfigParser() 
config.optionxform = str 
config_file = open("file.cfg", encoding="cp1251") 
config.readfp(config_file) 
+0

非常感谢。真 –