2017-09-25 335 views
0

Python 3.1.3 我需要的是使用ConfigParser從cp1251文件中讀取字典。 我的例子:ConfigParser中的編碼(Python)

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。 我tryed這一點:

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

但錯誤"'utf8' codec can't decode byte 0xcf in position 0"出現。 如果我使用.decode('','ignore') - 我只丟失了幾乎所有的配置文件。 我該怎麼辦?

+1

'config.read(「file.cfg」,encoding =「cp1251」)' – Goyo

+0

聽起來不錯,不起作用。已經嘗試過。由於Python3.x沒有「編碼」屬性。編碼從.open()默認設置繼承。 –

+0

屬性與什麼有關? 'ConfigParser.read'至少從[python 3.3](https://docs.python.org/3.3/library/configparser.html#configparser.ConfigParser.read)有一個'encoding'關鍵字參數。我希望你沒有使用舊版本。 – Goyo

回答

2

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) 
+0

非常感謝。真 –