python中config方法作用_python解析模块(ConfigParser)使用方法

很多软件都有配置文件,今天介绍一下python ConfigParser模块解析配置文件的使用方法

测试配置文件test.conf内容如下:

代码如下:

[first]

w = 2

v: 3

c =11-3

[second]

sw=4

test: hello

测试配置文件中有两个区域,first和second,另外故意添加一些空格、换行。

下面解析:

代码如下:

>>> import ConfigParser

>>> conf=ConfigParser.ConfigParser()

>>> conf.read('test.conf')

['test.conf']

>>> conf.sections()   #获得所有区域

['first', 'second']

>>> for sn in conf.sections():

...    print conf.options(sn)      #打印出每个区域的所有属性

...

['w', 'v', 'c']

['sw', 'test']

获得每个区域的属性值:

代码如下:

for sn in conf.sections():

print sn,'-->'

for attr in conf.options(sn):

print attr,'=',conf.get(sn,attr)

输出:

代码如下:

first -->

w = 2

v = 3

c = 11-3

second -->

sw = 4

test = hello

好了,以上就是基本的使用过程,下面是动态的写入配置,

代码如下:

cfd=open('test2.ini','w')

conf=ConfigParser.ConfigParser()

conf.add_section('test')        #add a section

conf.set('test','run','false')

conf.set('test','set',1)

conf.write(cfd)

cfd.close()

上面是向test2.ini写入配置信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
configparser模块是一个用于读取和写入配置文件的Python标准模块。配置文件通常是用于存储应用程序的设置和配置信息的文件。下面是使用configparser模块的基本步骤: 1. 导入configparser模块: ```python import configparser ``` 2. 创建一个ConfigParser对象: ```python config = configparser.ConfigParser() ``` 3. 读取配置文件: ```python config.read('config.ini') ``` 4. 获取配置项的值: ```python value = config.get('section', 'option') ``` 其,section是配置文件的一个段落,option是段落的一个选项。例如,在以下配置文件: ``` [database] host = localhost port = 3306 user = root password = test123 database = testdb ``` 要获取host的值,可以使用以下代码: ```python host = config.get('database', 'host') print(host) # 输出:localhost ``` 5. 修改配置项的值: ```python config.set('section', 'option', 'new_value') ``` 例如,要将host修改为127.0.0.1,可以使用以下代码: ```python config.set('database', 'host', '127.0.0.1') ``` 6. 写入配置文件: ```python with open('config.ini', 'w') as f: config.write(f) ``` 完整示例: ```python import configparser config = configparser.ConfigParser() # 读取配置文件 config.read('config.ini') # 获取配置项的值 host = config.get('database', 'host') port = config.getint('database', 'port') user = config.get('database', 'user') password = config.get('database', 'password') database = config.get('database', 'database') print('host:', host) print('port:', port) print('user:', user) print('password:', password) print('database:', database) # 修改配置项的值 config.set('database', 'host', '127.0.0.1') # 写入配置文件 with open('config.ini', 'w') as f: config.write(f) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值