简体   繁体   English

使用configparser解析ini文件会给出configparser.MissingSectionHeaderError以'ÿþ\\ n'作为第一行

[英]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. 我从ini文件的[.ShellClassInfo]部分读取变量时遇到问题。

My ini file: (with an empty break above and below) 我的ini文件:(上下有一个空白)

[.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? 有谁知道如何解决这个问题?

The error you provided contains information about the first line having those weird 'ÿþ\\n' symbols. 您提供的错误包含有关带有那些奇怪的'ÿþ\\n'符号的第一行的信息。
ÿþ is in fact a Byte order mark (BOM) of UTF-16 encoding. ÿþ事实上是一个字节顺序标记(BOM) UTF-16编码的。 (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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM