Operating Environment: Windows7.1
There are encoding parameters in Python 3, but for files that have a BOM (such as a notepad specified as Utf-8 under Windows), you need to use Utf-8-sig, and the utf-8 will not work.
Configuration file (utf-8 format, with BOM)
[Test]a = Chinese
Python3 the following code:
#-*-coding:utf-8-*-import configparserconfig = Configparser. Configparser () config.read (' Test.cfg.txt ', encoding= "Utf-8-sig") #,encoding= "Utf-8" Print (config[' test ' [' a '])
Python2 the following code:
#-*-Coding:utf-8-*-import configparserimport codecsconfig = Configparser.configparser () with Codecs.open (' Test.cfg.txt ', encoding= "Utf-8-sig") as F:CONFIG.READFP (f) Print (Config.get ("Test", "a"))
Error using Utf-8:
Configparser. Missingsectionheadererror:file contains no section headers.
File: ' Test.cfg ', line:1
' \ufeff[test]\n '
This problem is not in Linux.
Configparser reading a configuration that contains Chinese (Windows)