ConfigParser(Python)中的编码

2024-05-13 18:24:30 发布

您现在位置: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文件中的单词。但有时它不起作用(例如,使用“新行回车”符号)。 我的文件是UTF-8,配置文件(字典)是CP1251。好像有麻烦,我得把config解码成UTF-8。 我试过了:

^{pr2}$

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


Tags: 文件inconfig字典配置文件databaseconfigparserutf
1条回答
网友
1楼 · 发布于 2024-05-13 18:24:30

python3.1处于Python版本的无人区。理想情况下,您应该升级到python3.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)

相关问题 更多 >