Python configparser read the configuration file and resolve the error ConfigParser.MissingSectionHeaderError:File contains no section headers method

Source: Internet
Author: User
Tags xpath

Let me talk about the problem of reporting errors when reading the configuration file--ConfigParser.MissingSectionHeaderError: File contains no section headers

Problem Description:

When practicing ConfigParser to read configuration files, cmd kept reporting an error: ConfigParser.MissingSectionHeaderError: File contains no section headers.

D:\test_python>python task_test.py
Traceback (most recent call last):
  File "task_test.py", line 20, in <module>
    pp=ParsePageObjectRepositoryConfig()
  File "task_test.py", line 9, in __init__
    self.cf.read("D:\\test_python\\dataDriven\\conf\\PageObjectRepository.ini")
  File "C:\Python27\lib\ConfigParser.py", line 305, in read
    self._read(fp, filename)
  File "C:\Python27\lib\ConfigParser.py", line 512, in _read
    raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: D:\test_python\dataDriven\conf\PageObjectRepository.ini, line: 1
'\xef\xbb\xbf#\xe6\xaf\x8f\xe4\xb8\xaa\xe9\xa1\xb5\xe9\x9d\xa2\xe7\x94\xa8\xe4\xb8\x80\xe4\xb8\xaasection \xe6\xa0\x87\xe8\xaf\x86\n'

Baidu took a look at the online solutions,

The error is reported because the configuration file PageObjectRepository.ini is edited by notepad under windows and saved as UTF-8 or unicode format, two bytes "\xff\xfe" or three bytes "\xef" will be added to the beginning of the file \xbb\xbf". That's--"BOM

The solution is to remove the DOM bytes before the configuration file is read.

There is also a function on the Internet to remove the BOM byte with regularity: it is to replace the corresponding byte with an empty string

The remove_BOM() function definition:

def remove_BOM(config_path):
    content = open(config_path).read()
    content = re.sub(r"\xfe\xff","", content)
    content = re.sub(r"\xff\xfe","", content)
    content = re.sub(r"\xef\xbb\xbf","", content)
    open(config_path, ‘w’).write(content)

Post my configuration file and the code to read the configuration file below--:

 

Code:

#encoding=utf-8
from ConfigParser import ConfigParser
import re

def remove_BOM(config_path):#Remove the BOM byte at the beginning of the configuration file
    content = open(config_path).read()
    content = re.sub(r"\xfe\xff","", content)
    content = re.sub(r"\xff\xfe","", content)
    content = re.sub(r"\xef\xbb\xbf","", content)
    open(config_path, ‘w’).write(content)

class ParsePageObjectRepositoryConfig(object):
    def __init__(self,config_path):
        self.cf=ConfigParser()#Generate parser
        self.cf.read(config_path)
        print "-"*80
        print "cf.read(config_path):\n", self.cf.read(config_path)

    def getItemsFromSection(self,sectionName):
        print self.cf.items(sectionName)
        return dict(self.cf.items(sectionName))

    def getOptionValue(self,sectionName,optionName):#return a dictionary
        return self.cf.get(sectionName,optionName)

 

if __name__==‘__main__’:
    remove_BOM("D:\\test_python\\PageObjectRepository.ini")
    pp=ParsePageObjectRepositoryConfig("D:\\test_python\\PageObjectRepository.ini")
    remove_BOM
    print "-"*80
    print "items of ‘126mail_login’:\n",pp.getItemsFromSection("126mail_login")
    print "-"*80
    print "value of ‘login_page.username’ under section ‘126mail_login’:\n",pp.getOptionValue("126mail_login","login_page.username")

 

result:

D:\test_python>python task_test.py
-------------------------------------------------- ------------------------------
cf.read(config_path):
[‘D:\\test_python\\PageObjectRepository.ini’]
-------------------------------------------------- ------------------------------
items of ‘126mail_login’:
[('login_page.frame','id>x-URS-iframe'), ('login_page.username', "xpath>//input[@name='email']"), ('login_page.password', "xpath>//input[@name='password']"), ('login_page.loginbutton','id>dologin')]
{'login_page.loginbutton':'id>dologin','login_page.username': "xpath>//input[@name='email']",'login_page.frame':'id>x-URS-iframe' ,'login_page.password': "xpath>//input[@name='password']"}
-------------------------------------------------- ------------------------------
value of ‘login_page.username’ under section ‘126mail_login’:
xpath>//input[@name=‘email’]

 

Python ConfigParser reads the configuration file and solves the error ConfigParser.MissingSectionHeaderError: File contains no section headers

Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.