Loading

模块之ConfigParser模块详解

ConfigParser模块介绍

在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍。
ConfigParser解析的配置文件的格式为.ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项。

配置文件格式如下:

  • 中括号“[ ]”内包含的为section。
  • section 下面为类似于key-value 的配置内容。

[HOST]  
HOST1 = 172.25.254.1:root:123
HOST2 = 172.25.254.2:root:123
HOST3 = 172.25.254.3:root:123

[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = westos

 

ConfigParser模块初始化

import configparser  # 导入模块

config = configparser.ConfigParser()  # 实例化ConfigParser对象
config.read('test.ini')  # 读取配置文件

 

ConfigParser模块常用方法

查看节点

# 获取sections
print(config.sections())

# 获取某一sections下的所有的options
print(config.options('db'))

# 获取某一sections下的items
print(config.items('db'))

# 获取某一具体的value值
res = config.get('db', 'db_host')
print(res, type(res))

检查节点

# 检查文件中是否存在某个节点。如果存在,返回True;否则,返回False;
config.has_section("db")  # True

config.has_section("port")  # False


# 检查文件中的某个节点是否存在某个key(eg:db_pass);如果存在,返回True;否则,返回False;
config.has_option("db","db_pass")  # True

config.has_option("db","db_passwd")  # False

添加节点

# 添加指定的节点
config.add_section("info")

# 往节点里面添加对应的key-value值;
config.set("info","username","root")
config.set("info","password","westos")

# 将添加的内容真正写入文件中;
config.write(open("config.ini","w"))

删除节点

# 删除指定节点中的key值;如果成功删除,返回True,否则,返回False;
config.remove_option("info","password")  # True
config.remove_option("info","username")  # True

# 删除指定的节点;
conf.remove_section("info")  # True

# 将删除的内容在文件中真正删除;
config.write(open("config.ini","w"))

 

posted @ 2020-07-10 16:19  愚者丶  阅读(395)  评论(0编辑  收藏  举报