python中configparser模块

本文详细介绍了Python中ConfigParse模块的基本用法,包括如何读取配置文件、获取指定配置项的值、判断节点是否存在、添加及删除节点等操作,并提供了丰富的示例代码。

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

python中的configparse模块的使用

主要用来解析一些常用的配置,比如数据配置等。

例如:有一个dbconfig.ini的文件

 1 [section_db1]
 2 db = test_db1
 3 host = 127.0.0.1
 4 port = 3319
 5 user = root
 6 password = 123456
 7 
 8 [section_db2]
 9 db = test_db2
10 host = 127.0.0.1
11 port = 3318
12 user = root
13 password = 123456
14 
15 [section_db5]
16 db = test_db5

 常用操作代码:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Eric.yue

import configparser
conf = configparser.ConfigParser()

'''
读取操作
'''
#获取section
conf.read('dbconfig.ini')
ret = conf.sections()
print ret
#[u'section_db1', u'section_db2']

#指定节点下所有的键
ret = conf.options('section_db1')
print ret #[u'db', u'host', u'port', u'user', u'password']

#获取指定的键值对
ret = conf.items('section_db1')
print ret
#[(u'db', u'test_db1'), (u'host', u'127.0.0.1'), (u'port', u'3319'), (u'user', u'root'), (u'password', u'123456')]


conf.read('dbconfig.ini') #文件路径
dbname = conf.get("section_db1","db") #获取指定section的db
print dbname
port = conf.getint("section_db1","port") #获取指定section的port

print type(port)
#<type 'int'>

#判断节点是否存在
has_sec = conf.has_section('section_db2')
print has_sec #True

# 添加节点
#conf.add_section("section_db4")
#conf.set("section_db4", "db", "test_db4")

#conf.add_section("section_db5")
#conf.set("section_db5", "db", "test_db5")
#conf.write(open('dbconfig.ini', 'w'))

#删除节点,会把对应节点下面的东西都会删除掉
conf.remove_section("section_db4")
conf.write(open('dbconfig.ini', 'w'))

'''
写入配置文件操作
'''
'''
#修改
conf.read('dbconfig.ini') #文件路径
conf.set("section_db1", "db", "test_db1") #增加指定section 的option的db
conf.set("section_db1", "port", "3319")  #增加指定section 的option的port

#增加
conf.add_section("section_db3")    #增加section
conf.set("section_db3", "db", "test_db3")
conf.set("section_db3", "host", "127.0.0.1")
conf.set("section_db3", "port", "3319")
conf.set("section_db3", "user", "root")

#最后执行才操作
conf.write(open('dbconfig.ini', 'w'))
'''

 

转载于:https://www.cnblogs.com/gide/p/6248478.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值