【问题标题】:Encodings in ConfigParser (Python)ConfigParser (Python) 中的编码
【发布时间】:2017-09-25 13:49:05
【问题描述】:

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 中的配置文件(字典)。似乎很麻烦,我必须将配置解码为 UTF-8。 我试过这个:

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

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

【问题讨论】:

  • config.read("file.cfg", encoding="cp1251")
  • 听起来不错,但不起作用。已经试过了。由于 Python3.x 没有“编码”属性。编码继承自 .open() 默认设置。
  • 属性与什么有什么关系? ConfigParser.read 至少从 python 3.3 开始就有 encoding 关键字参数。我希望你没有使用旧版本。

标签: python dictionary encoding utf-8 configparser


【解决方案1】:

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)

【讨论】:

  • 非常感谢。真的
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 2014-02-16
  • 2012-05-26
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
相关资源
最近更新 更多