python基础-configparser模块使用

时间:2022-07-22
本文章向大家介绍python基础-configparser模块使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

configparser模块用来处理ini格式的配置文件,使用起来非常简单,使用方法如下:

import configparser
import sys

cfg = configparser.ConfigParser()    #初始化
cfg.read('/Users/fei/tmp/ops/test.ini')   #读取某ini文件

print(cfg.sections())    #获取所有节点
print(cfg.get('mysqld','datadir'))    #获取指定节点的指定key的值
print(cfg.getint('mysqld','port'))    

for k,v in cfg.items('mysqld'):    #获取某个节点下的所有key
    print(k,v)


cfg.set('mysqld','port','3308')    #修改某节点的值
cfg.set('mysql','sock','/opt/mysql.sock')
cfg.add_section('client')       #增加一个节点
cfg.set('client','user','mysql')
print(cfg.get('client','user'))
cfg.remove_option('client','user')   #删除某节点中的一个key
cfg.remove_section('client')    #删除某节点
cfg.write(sys.stdout)

运行结果

['mysql', 'mysqld', 'afei']
/usr/local/mysql/data
3306
a test
b dev
c prod
port 3306
datadir /usr/local/mysql/data
sql_mode NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
mysql
[DEFAULT]
a = test
b = dev
c = prod

[mysql]
default-character-set = utf8
sock = /opt/mysql.sock

[mysqld]
port = 3308
datadir = /usr/local/mysql/data
sql_mode = NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

[afei]
test1 = 2
test2 = 3

以上是使用的jupyter测试的,很方便的一个工具