Configparser模块

此模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

来看一个好多软件的常见配置文件格式如下

```cnf
[DEFAULT]
ServerAliveInterval = 45   
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
```

实例
1.写入配置文件:
import configparser
# 加载现有配置文件
conf = configparser.ConfigParser()
# 写入配置文件
conf.add_section('config') #添加section
# 添加值
conf.set('config', 'v1', '100')
conf.set('config', 'v2', 'abc')
conf.set('config', 'v3', 'true')
conf.set('config', 'v4', '123.45')
# 写入文件
with open('conf.ini', 'w') as fw:
conf.write(fw)

2.已生成配置文件:

[config]
v1 = 100
v2 = abc
v3 = true
v4 = 123.45
3.增删改查配置文件:
import configparser
config=configparser.ConfigParser()
config.sections()
config.read('conf.ini')
print(config['config']['v1']) #查
config['config']['v1']='1000' #改

config['config']['v5']='name' #增
config.set('config', 'v1', '100')

se=config.remove_section(config['config']['v1'])
print(se)
print(config['config']['v5'])
 
原文地址:https://www.cnblogs.com/sunny666/p/9828979.html