python之ConfigParser

本文介绍了如何利用Python中的configParser模块来高效地管理和操作配置文件。内容覆盖了读取配置文件、获取节点及键值对等基本操作,并展示了如何进行节点的检查、添加与删除。适用于希望简化配置文件管理流程的开发者。

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

以前傻傻的不知道还有configParser这么方便的模块,都是一个个的解析转换……

配置文件xxxxx

# 注释1

注释2

[section1] # 节点

k1 = v1    #

k2:v2       #

 

[section2] # 节点

k1 = v1    #

k2=['123','456']

节点必须是用[],节点下面的信息必须使用键值对

使用#和;都可以注释信息

 

1、获取所有节点       

import configparser

 

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding='utf-8')

ret = config.sections()

print ret

 

2、获取指定节点下所有的键值对     

import configparser

 

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding='utf-8')

ret = config.items('section1')

print ret

 

3、获取指定节点下所有的建      

import configparser

 

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding='utf-8')

ret = config.options('section1')

print ret

 

4、获取指定节点下指定key的值      

import configparser

 

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding='utf-8')

v = config.get('section1', 'k1')

 

5、检查、删除、添加节点     

import configparser

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding='utf-8')

# 检查

has_sec = config.has_section('section1')

print has_sec

 

# 添加节点(只要进行了修改,就必须回写,不然信息不保存)

config.add_section("SEC_1")

config.write(open(‘xxxxx’, 'w'))

#文件信息被写之后,注释信息自动消失

 

 #删除section或者option

config.remove_section("SEC_1")

config.write(open(‘xxxxx’, 'w'))

转载于:https://www.cnblogs.com/hellowcf/p/7238516.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值