Search code examples
pythoniniconfigparser

Parsing ini file with configparser gives configparser.MissingSectionHeaderError with 'ÿþ\n' as the first line


I'm having problems with reading a variable from the [.ShellClassInfo] section in a ini file.

My ini file: (with an empty break above and below)

[.ShellClassInfo]

IconResource=\\some_text

The way how I read text from the file:

import configparser

config = configparser.ConfigParser()
config.read('desktop.ini')
file = config.get('.ShellClassInfo', 'IconResource')
content = open(file, 'r').read()

In the rest of my script I check if some text is in the variable content.

But before I can check this, the following error raise:

configparser.MissingSectionHeaderError: File contains no section headers.
file: 'desktop.ini', line: 1
'ÿþ\n'

Does anyone know how to solve this problem?


Solution

  • The error you provided contains information about the first line having those weird 'ÿþ\n' symbols.
    ÿþ is in fact a Byte order mark (BOM) of UTF-16 encoding. (Found it here: link)

    According to documentation you can specify the encoding of the config file when reading it as follows:

    config = configparser.ConfigParser()
    config.read('desktop.ini', encoding='utf-16')