configparser.DuplicateOptionError: While reading from ‘D:\\PythonCharmProject\\Demo/config/config.in

python读取配置文件里面的浏览器的时候,当config.ini里面的浏览器的类型是多个的时候,读取异常。

config.ini文件:

[browserType]
browserName=Chorme
browserName=Ie  #IE浏览器类型
#browserName=Firefox   #火狐浏览器
[testServer]
URL=http://baidu.com

代码:

#coding=utf-8
import configparser
import os

class TestReadConfigFile(object):

    def get_value(self):

        root_dir=os.path.dirname(os.path.abspath('.'))
        print(root_dir)

        config=configparser.ConfigParser()
        file_path=os.path.dirname(os.path.abspath('.'))+'/config/config.ini'
        config.read(file_path,encoding='utf-8')

        browser=config.get('browserType','browserName')
        url=config.get('testServer','URL')

        return(browser,url)

trcf=TestReadConfigFile()
print(trcf.get_value())

返回的整体报错异常:

Traceback (most recent call last):
  File "D:\PythonCharmProject\Demo\test1\python读取配置文件.py", line 22, in <module>
    print(trcf.get_value())
  File "D:\PythonCharmProject\Demo\test1\python读取配置文件.py", line 14, in get_value
    config.read(file_path,encoding='utf-8')
  File "C:\Users\ttt\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 697, in read
    self._read(fp, filename)
  File "C:\Users\ttt\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 1093, in _read
    raise DuplicateOptionError(sectname, optname,
configparser.DuplicateOptionError: While reading from 'D:\\PythonCharmProject\\Demo/config/config.ini' [line  5]: option 'browsername' in section 'browserType' already exists

从报错中的大概看出是File "C:\Users\ttt\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 697, in read
    self._read(fp, filename),读取的异常,然后进

Configuration.py

这个里面看一下。

搜索‘DuplicateOptionError’,找到这个类,然后大概看下代码的内容,里面的注释部分如果英语不好可以百度翻译一下,起码知道个大概意思。

然后在这个类里面的函数都点进去看看,不懂就百度

    def __init__(self, section, option, source=None, lineno=None):
        msg = [repr(option), " in section ", repr(section),
               " already exists"]
        if source is not None:
            message = ["While reading from ", repr(source)]
            if lineno is not None:
                message.append(" [line {0:2d}]".format(lineno))
            message.append(": option ")
            message.extend(msg)
            msg = message
        else:
            msg.insert(0, "Option ")
        Error.__init__(self, "".join(msg))
        self.section = section
        self.option = option
        self.source = source
        self.lineno = lineno
        self.args = (section, option, source, lineno)

里面的东西正好可以和报错对上,section对应的config.ini里面的中括号扩起来的browserType,option对应的就是browsername

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值