ini文件是Initialization File的缩写,平时用于存储软件的的配置文件。例如:MySQL数据库的配置文件。
# 文件名为my.ini [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock log-bin=py-mysql-bin character-set-server=utf8 collation-server=utf8_general_ci log-error=/var/log/mysqld.log# Disabling symbolic-links is recommended to prevent assorted security riskssymbolic-links=0 [mysqld_safe] log-error=/var/log/mariadb/mariadb.log pid-file=/var/run/mariadb/mariadb.pid [client] default-character-set=utf8
1.查看所有节点(sections函数)
import configparser config = configparser.ConfigParser()config.read('my.conf', encoding='utf-8')ret = config.sections()print(ret) >>输出 ['mysqld', 'mysqld_safe', 'client']
2.读取节点下的键值(items函数)
import configparser config = configparser.ConfigParser() config.read('my.conf', encoding='utf-8') item_list = config.items("mysqld_safe")print(item_list) >>输出 [('log-error', '/var/log/mariadb/mariadb.log'), ('pid-file', '/var/run/mariadb/mariadb.pid')]
3.读取节点下值(根据 节点+键 )(get函数)
import configparser config = configparser.ConfigParser() config.read('my.ini' , encoding='utf-8') value = config.get('mysqld', 'log-bin')print(value)>>输出 py-mysql-bin
4.检查、删除、添加节点
import configparser config = configparser.ConfigParser()config.read('my.ini', encoding='utf-8')# 检查has_sec = config.has_section('mysqld')print(has_sec)# 添加节点config.add_section("SEC_1")# 节点中设置键值config.set('SEC_1', 'k10', "123") config.set('SEC_1', 'name', "哈哈哈哈哈") config.add_section("SEC_2") config.set('SEC_2', 'k10', "123")# 内容写入新文件config.write(open('xxoo.conf', 'w'))# 删除节点config.remove_section("SEC_2")# 删除节点中的键值config.remove_option('SEC_1', 'k10') config.write(open('new.conf', 'w'))