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')
-我只会丢失几乎所有的配置文件。
我该怎么办?在
python3.1处于Python版本的无人区。理想情况下,您应该升级到python3.5,这样您就可以
config.read("file.cfg", encoding="cp1251")
如果必须使用3.1x,则可以使用
ConfigParser.readfp()
方法使用正确的编码从以前打开的文件中读取:相关问题 更多 >
编程相关推荐