configparser 模块

此模块用于生成和修改常见的配置文件,在python2中次模块叫 ConfigParser

 

很多软件的常见配置文件格式如下:

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

[bitbucket.org]
User = hg

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

 

使用configparser解析配置文件:

import configparser

config = configparser.ConfigParser()  # 实例化(生成对象)
print(config.sections())  # 调用section方法,输出为: []
print(config.read("config.ini"))  # 输出为:['config.ini']
print(config.sections())  # 再次调用section方法,默认不会读取DEFAULT,输出为: ['bitbucket.org', 'topsecret.server.com']
print("bitbucket.org" in config)  # 判断元素是否在section列表里,输出为:True

print(config["bitbucket.org"]["User"])  # 通过字典形式取值,获取 User的值,输出为:hg
# 通过字典取值,或者如下,一样的:
bit = config["bitbucket.org"]
print(bit["User"])

# 遍历  bitbucket.org 字典的key
for key in config["bitbucket.org"]:
    print(key)
# 注意:以上会打印出 bitbucket.org 下的key user,但同时也会打印出DEFAULT下的所有key
# 输出为:
user
serveraliveinterval
compression
compressionlevel
forwardx11

 

其他增删改查的语法:

初始配置文件内容如下:

[group1]
k1 = v1
k2:v2
k3=3

[group2]
k1 = v1

说明:支持两种方式的分隔符 “=” 和 “:” 

 

读操作:

import configparser

config = configparser.ConfigParser()
config.read("conf.ini")

# 读
secs = config.sections()
print(secs)  # 输出:['group1', 'group2']

options = config.options("group2")  # 获取指定section的keys
print(options)  # 输出:['k1']

item_list = config.items("group2")  # 获取指定 section的keys和values,key value已 以元组形式
print(item_list)  # 输出:[('k1', 'v1')]

val = config.get("group1", "k1")  # 获取指定的 key的value
print(val)  # 输出:v1

val2 = config.getint("group1", "k3")  # 将获取到的值转为int
print(val2)  # 输出:3

 

# 增删改操作:

import configparser

config = configparser.ConfigParser()
config.read("conf.ini")

# 查看有没有指定的section
sec = config.has_section("wupeiqi")  # 看有没有wupeiqi
print(sec)  # 输出:False  说明没有

# 增加
config.add_section("wupeiqi")  # 添加 wupeiqi
config.write(open("conf.ini", "w", encoding="utf-8"))  # 将添加操作写入文件

# 修改
config.set("group2", "k1", "11111")  # 将group2的k1的值改为11111
config.write(open("conf.ini", "w", encoding="utf-8"))  # 将添加操作写入文件

# 删除
sec2 = config.remove_section("group1")  # 删除section 并返回状态 True或False
print(sec)  # 输出:True , 删除成功
config.write(open("conf.ini", "w", encoding="utf-8"))  # 将对应的删除操作写入文件

 

 

版权声明:
作者:admin
链接:https://www.chenxie.net/archives/1816.html
来源:蜀小陈
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>