常用模块之--configparser

configparser.ini配置文件内容:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

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

 

# _*_ coding:utf-8 _*_
# Author: daihaijun
import configparser
config_file = "configparser.ini"
# 创建对象
config = configparser.ConfigParser()
# 读取配置文件
config.read(config_file)

"""查询"""
# 获取所有的section,包括DEFAULT
print("All sections:",list(config.keys()))
sec_all = list(config.keys())
# 获取配置文件的sections name(不包括默认section:default)
sec_list = config.sections()
print("sections excluding DEFAULT:",sec_list)
# 获取DEFAULT section的内容:以字典形式输出所有items
print(dict(config.defaults()))

# 获取key的方法:
print(list(config[sec_list[0]])) # 除了输出bitbucket.org这个section自己的key之外,还会输出所有的全局key(DEFAULT中的key)
print(config.options(sec_list[0])) # 同上,其实就是调用的上面list函数

# 获取key/value的方法
print(dict(config[sec_list[0]])) # 输出key,value

# 单独获取某个key的value的方法:
config['topsecret.server.com']['port']
config.options('topsecret.server.com','port')

"""通过上面一系列方法就可以读取到配置文件里的任何内容了,当然还有其他的方法比如config.get"""

# 判断某个section中是否存在某个key: 不区分大小写
if "user" in config[sec_list[0]]:
print("name in bitbucket.org section")

""" 增删改操作 """
# 1. 删除整个section(包括所属items)
config.remove_section('topsecret.server.com') # 删除section 并返回状态(true, false)
config.write(open(config_file,'w')) # 执行写入操作文件正式生效
# 2. add section
config.has_section('topsecret.server.com') # 判断是否存在该section
config.add_section('topsecret.server.com') # add section
config.write(open(config_file,'w'))

# 3. 增加或者修改某个key:不存在则添加,已存在则修改其value.
config.set('topsecret.server.com','Port','50022')
config.write(open(config_file,'w'))

# 4. 删除某个key
config.has_option('topsecret.server.com','port') # 判断key是否存在
config.remove_option('topsecret.server.com','port')
config.write(open(config_file,'w'))
posted @ 2018-07-21 16:25  念宗  阅读(93)  评论(0编辑  收藏  举报