今天使用ConfigParser解析一個ini文件,報出如下錯誤:
config.read(logFile)
File "C:\Python26\lib\ConfigParser.py", line 286, in read
self._read(fp, filename)
File "C:\Python26\lib\ConfigParser.py", line 482, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
MissingSectionHeaderError: File contains no section headers.
file: C:\test\test.ini, line: 1
'\xff\xfe\r\x00\n'
經過分析是由於文件編碼方式導致,調整代碼如下,問題解決:
def test():
logFile = r'C:\test\test.ini'
config = ConfigParser.ConfigParser()
config.readfp(codecs.open(logFile, "r", "utf_16"))
print config.sections()
此文件為unicode編碼,所以這里填入"utf_16",如果為其他編碼格式,則修改該參數。
python編碼查詢地址:http://docs.python.org/2/library/codecs.html?highlight=streamcodec#standard-encodings

