ConfigParser 中的编码 (Python)

Encodings in ConfigParser (Python)

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 文件中的一些单词。但有时它不起作用(例如,使用 "new line-carriage return" 的符号)。 我的 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') - 我只会丢失几乎所有的配置文件。 我该怎么办?

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)