ConfigParser MissingSectionHeaderError: File contains no section headers.


今天使用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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM