0081-【Python包】-ConfigObj-参数配置文件

本文详细介绍如何使用Python的ConfigObj库进行配置文件的创建、读取、修改、添加及删除操作。ConfigObj允许用户轻松地处理多级结构的数据,支持列表和注释,适用于各种配置需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装

pip install configobj

资源

github: https://github.com/DiffSK/configobj/blob/master/docs/configobj.rst
帮助手册: https://configobj.readthedocs.io/en/latest/configobj.html


github官网例子

$cat write.py
from configobj import ConfigObj
config = ConfigObj()
config.filename = "./write1.config"
# 一级结构写入
config['keyword1'] = "aaa"
config['keyword2'] = "bbb"
# 二级结构写入
config['section1'] = {}
config['section1']['keyword3'] = 111
config['section1']['keyword4'] = 222
# 三级结构写入
section2 = {
    'keyword5': "ccc",
    'keyword6': "ddd",
    'sub-section': {
        'keyword7': "eee"
        }
}
config['section2'] = section2
# 列表写入
config['section3'] = {}
config['section3']['keyword 8'] = [111, 222, 333]
config['section3']['keyword 9'] = [444, 555, 666]
#
config.write()

显示

$cat write1.config
keyword1 = aaa
keyword2 = bbb
[section1]
keyword3 = 111
keyword4 = 222
[section2]
keyword5 = ccc
keyword6 = ddd
[[sub-section]]
keyword7 = eee
[section3]
keyword 8 = 111, 222, 333
keyword 9 = 444, 555, 666

$cat read1.py
from configobj import ConfigObj
config = ConfigObj("write1.config")
#
value1 = config['keyword1']
value2 = config['keyword2']
print("value1 :",value1)
print("value2 :",value2)
#
section1 = config['section1']
value3 = section1['keyword3']
value4 = section1['keyword4']
print("section1 :",section1)
print("value3 :",value3)
print("value4 :",value4)
#
# you could also write
value3 = config['section1']['keyword3']
value4 = config['section1']['keyword4']
print("value3 :",value3)
print("value4 :",value4)

显示

$python read1.py
value1 : aaa
value2 : bbb
section1 : {'keyword3': '111', 'keyword4': '222'}
value3 : 111
value4 : 222
value3 : 111
value4 : 222

config

关键字和值之间用“=”分隔,而部分标记位于方括号之间。 关键字,值和节名称可以用单引号或双引号括起来。 缩进并不重要,但可以保留。

通过重复节标记中的方括号来指示小节。 您可以使用更多括号来嵌套级别。

您可以通过使用逗号分隔项目来获取列表值,并使用三引号(单引号或双引号)跨越多行。

# This is the 'initial_comment'
# Which may be several lines
keyword1 = value1
'keyword 2' = 'value 2'

[ "section 1" ]
# This comment goes with keyword 3
keyword 3 = value 3
'keyword 4' = value4, value 5, 'value 6'

    [[ sub-section ]]    # an inline comment
    # sub-section is inside "section 1"
    'keyword 5' = 'value 7'
    'keyword 6' = '''A multiline value,
that spans more than one line :-)
The line breaks are included in the value.'''

        [[[ sub-sub-section ]]]
        # sub-sub-section is *in* 'sub-section'
        # which is in 'section 1'
        'keyword 7' = 'value 8'

[section 2]    # an inline comment
keyword8 = "value 9"
keyword9 = value10     # an inline comment
# The 'final_comment'
# Which also may be several lines

ConfigObj specifications参数

config = ConfigObj(infile=None, options=None, configspec=None, encoding=None,
                   interpolation=True, raise_errors=False, list_values=True,
                   create_empty=False, file_error=False, stringify=True,
                   indent_type=None, default_encoding=None, unrepr=False,
                   write_empty_values=False, _inspec=False)


案例

创建配置文件

$cat test.conf
[server]
servername = 192.168.11.1
serverport = 8000

[client_srv]
# 这里是注释
server = localhost
port = 8000


读取配置文件

$cat read.py
from configobj import ConfigObj
#
conf_ini = "./test.config"
config = ConfigObj(conf_ini,encoding='UTF8')
#
# 读配置文件
#
print(config['server'])
print(config['server']['servername'])

显示结果:
如果方括号下面有多个选项,则为字典,如果索引到终选项,则为文本

$python read.py
{'servername': '192.168.11.1', 'serverport': '8000'}
192.168.11.1

修改文件

from configobj import ConfigObj
#
conf_ini = "./test.ini"
config = ConfigObj(conf_ini,encoding='UTF8')
config['server']['servername'] = "127.0.0.1"
config.write()

显示

$cat test.config
[server]
servername = 127.0.0.1


添加新项

from configobj import ConfigObj
#
conf_ini = "./test.ini"
config = ConfigObj(conf_ini,encoding='UTF8')
config['new_items'] = {}
config['new_items']['Items1'] = "test items"
config.write()

显示

[new_items]
Items1 = test items

删除某一项

from configobj import ConfigObj
#
conf_ini = "./test.ini"
config = ConfigObj(conf_ini,encoding='UTF8')
del config['client_srv']['port']
config.write()

显示

[client_srv]
# 这里是注释
server = localhost

将配置文件写入到不同的文件中

from configobj import ConfigObj
#
conf_ini = "./test.ini"
config = ConfigObj(conf_ini,encoding='UTF8')
config.filename = "./test1.ini"
config.write()

显示

$cat test1.config
[server]
servername = 127.0.0.1
serverport = 8000

[client_srv]

server = localhost
[new_items]
Items1 = test items


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值