ConfigParser模块
1、ConfigParser模块
configparser是Python的标准库之一,主要用来解析.config
和.ini
配置文件
config配置文件由两部分组成:sections和items
sections用来区分不同的配置块,[]
中为section;items是sections下面的键值,可以使用=
或:
分隔
例如test.config
文件:
[lang]
name=中文简体
[mysql]
host=localhost
port=3306
user:root
password:123456
2、读取与解析
from configparser import ConfigParser
# 初始化
parser = ConfigParser()
parser.read(r'C:\Users\cc\Desktop\test.config', encoding='utf-8')
# 获取所有sections
print(parser.sections()) # ['lang', 'mysql']
# 获取指定section的items
print(parser.items('mysql')) # [('host', 'localhost'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
# 获取指定section对应K的V
print(parser.get('mysql', 'port')) # 3306
# 获取第n个section的所有K
print(parser.options(parser.sections()[1])) # ['host', 'port', 'user', 'password']
3、写入
parser['logging'] = {
"level": '2',
"path": "/root"
}
# 若是同一个ConfigParser对象,则追加写入
with open(r'C:\Users\cc\Desktop\test.config', 'w') as conf:
parser.write(conf)
4、修改
parser.set('mysql', 'user', 'blue')
print(parser.get('mysql', 'user')) # blue