先说一下在读取配置文件时报错的问题--ConfigParser.MissingSectionHeaderError: File contains no section headers

问题描述:

在练习ConfigParser读取配置文件时,cmd一直报一个错: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'

百度了一下网上的解决方案,

报错是因为配置文件PageObjectRepository.ini在windows下经过notepad编辑后保存为UTF-8或者unicode格式的话,会在文件的开头加上两个字节“\xff\xfe”或者三个字节“\xef\xbb\xbf”。 就是--》BOM, BOM是什么?请看结尾

解决的办法就是在配置文件被读取前,把DOM字节个去掉。

网上也给了一个用正则去掉BOM字节的函数:就是把对应的字节替换成空字符串

remove_BOM()函数定义:

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)

下面贴一下我的配置文件和读取配置文件的代码--:

代码:

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

def remove_BOM(config_path):#去掉配置文件开头的BOM字节
    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()#生成解析器
        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 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")

结果:

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']

BOM概念:

BOM(Byte Order Mark),字节顺序标记,出现在文本文件头部,Unicode编码标准中用于标识文件是采用哪种格式的编码。
UTF-8 不需要 BOM 来表明字节顺序,但可以用 BOM 来表明编码方式。字符 “Zero Width No-Break Space” 的
UTF-8 编码是 EF BB BF。所以如果接收者收到以 EF BB BF 开头的字节流,就知道这是 UTF-8编码了。Windows
就是使用 BOM
来标记文本文件的编码方式的。类似WINDOWS自带的记事本等软件,在保存一个以UTF-8编码的文件时,会在文件开始的地方插入三个不可见的字符(0xEF
0xBB 0xBF,即BOM)。它是一串隐藏的字符,用于让记事本等编辑器识别这个文件是否以UTF-8编码。

从堆栈信息中可以看到UTF8编码的字符有BOM的字符串前边有:\xef\xbb\xbf

'\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'

python ConfigParser读取配置文件,及解决报错(去掉BOM)ConfigParser.MissingSectionHeaderError: File contains no section headers的方法的更多相关文章

  1. ConfigParser.MissingSectionHeaderError: File contains no section headers.

    今天使用ConfigParser解析一个ini文件,报出如下错误: config.read(logFile) File "C:\Python26\lib\ConfigParser.py&qu ...

  2. python在读取配置文件存入列表中,去掉回车符号

    self.receiver = map(lambda x: x.strip(), receiver_list) # 去掉list中的回车符号

  3. 记一次用python 的ConfigParser读取配置文件编码报错

    记一次用python 的ConfigParser读取配置文件编码报错 ...... raise MissingSectionHeaderError(fpname, lineno, line)Confi ...

  4. ConfigParser读取配置文件时报错:ConfigParser.MissingSectionHeaderError

    使用ConfigParser来读取配置文件,经常会发现经过记事本.notepad++修改后的配置文件读取时出现下面的问题: ConfigParser.MissingSectionHeaderError ...

  5. python之读取配置文件模块configparser(二)参数详解

    configparser.ConfigParser参数详解 从configparser的__ini__中可以看到有如下参数: def __init__(self, defaults=None, dic ...

  6. Python读取CSV文件,报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa7 in position 727: illegal multibyte sequence

    Python读取CSV文件,报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa7 in position 727: illegal mul ...

  7. python中引入包的时候报错AttributeError: module 'sys' has no attribute 'setdefaultencoding'解决方法?

    python中引入包的时候报错:import unittestimport smtplibimport timeimport osimport sysimp.reload(sys)sys.setdef ...

  8. python中读取配置文件ConfigParser

    在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介 ...

  9. DB2读取CLOB字段-was报错:操作无效:已关闭 Lob。 ERRORCODE=-4470, SQLSTATE=null

    DB2读取CLOB字段-was报错:操作无效:已关闭 Lob. ERRORCODE=-4470, SQLSTATE=null 解决方法,在WAS中要用的数据源里面配置连个定制属性: progressi ...

随机推荐

  1. Redis(五)-- Java API

    一.pox.xml <dependencies> <dependency> <groupId>redis.clients</groupId> <a ...

  2. 什么叫做hack

    由于不同的浏览器,比如Internet Explorer 6,Internet Explorer 7,Mozilla Firefox等,对CSS的解析认识不一样,因此会导致生成的页面效果不一样,得不到 ...

  3. Window PHP 使用命令行模式

    电脑系统: win7 php环境: phpstudy 1 把php目录放到环境变量path下面: 我的电脑->属性->高级->环境变量->系统变量->Path->编 ...

  4. hihocoder [Offer收割]编程练习赛14 小Hi和小Ho的礼物

    题目1 : 小Hi和小Ho的礼物 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 某人有N袋金币,其中第i袋内金币的数量是Ai.现在他决定选出2袋金币送给小Hi,再选2袋 ...

  5. 二、微信小游戏开发 多线程Worker

    微信多线程Worker教程 微信多线程Worker API 一.创建Worker,并和当前线程通讯 多线程worker只能创建1个.能和当前线程互传数据. 创建worker 在微信开发者工具中,在当前 ...

  6. Egret资源管理解决方案

    关于egret开发H5页游,资源管理和加载的一点看法. 一 多json文件管理 二 资源归类和命名 三 exml文件编写规范 四 资源预加载.分步加载.偷载 五 资源文件group分组 六 ResUt ...

  7. 【Android】 ImageView.ScaleType设置图解

    ImageView的Scaletype决定了图片在View上显示时的样子,如进行何种比例的缩放,及显示图片的整体还是部分,等等. 设置的方式包括: 1. 在layout xml中定义android:s ...

  8. 【转载】国外程序员整理的Java资源大全

    以下转载自: 推荐!国外程序员整理的Java资源大全中文版    https://github.com/akullpp/awesome-java英文版 Java 几乎是许多程序员们的入门语言,并且也是 ...

  9. LOL TGP更新影响VS debug 问题

    刚才看群里说到VS无法调试,出现"无法使用xxx附加到应用程序'webdev.webserver...'"的问题,群友提出自己的经历,可能是LOL TGP的问题. 提问者卸载了TG ...

  10. Oracle数据类型number

    oracle数值类型只有number number(变长) 1.number可以存放整数,可以存放小数: 2.number(p,s) 说明: p表示有效位,s为小数位:范围p[1,38],s[-84, ...