ConfigParser(Python)中的编码
Python 3.1.3 我需要的是使用ConfigParser从cp1251文件读取字典。 我的例子是:ConfigParser(Python)中的编码,python,dictionary,encoding,utf-8,configparser,Python,Dictionary,Encoding,Utf 8,Configparser,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 = Ds
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'编解码器无法对位置0的字节0xcf进行解码”。
如果我使用.decode(“”,'ignore')
-我几乎丢失了所有配置文件。
我该怎么办?Python 3.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)
Python 3.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)
config.read(“file.cfg”,encoding=“cp1251”)
听起来不错,但不起作用。已经试过了。由于Python3.x没有“编码”属性。编码是从.open()默认设置继承的。属性与任何东西有什么关系ConfigParser.read
至少从那时起就有一个encoding
关键字参数。我希望您没有使用旧版本。config.read(“file.cfg”,encoding=“cp1251”)
听起来不错,但不起作用。已经试过了。由于Python3.x没有“编码”属性。编码是从.open()默认设置继承的。属性与任何东西有什么关系ConfigParser.read
至少从那时起就有一个encoding
关键字参数。我希望您没有使用旧版本。非常感谢。真的非常感谢。真正地