configparser配置文件模块

1、configparser的作用

mysql等很多文件的配置如下:

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

[bitbucket.org]
User = hg

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

如何用python生成和更改类似的配置文件,需要使用configparser模块,是python3的内置模块,可以直接导入

2、如何写一个配置文件

方法:add_section(section) 添加一个新的section

import configparser
config = configparser.ConfigParser()
config = configparser.ConfigParser()  #生成一个对象
print(type(config))

#默认会有DEFAULT节点
config["DEFAULT"] = {
    'ServerAliveInterval': 45,
    'Compression': 'yes',
    'CompressionLevel': '9'
}  #感觉有点像字典的配置,哈哈,给默认的DEFAULT

#新增节点
config.add_section('hello.org')
config.set('hello.org','IP','192.168.9.12')

config['bitbucket.org'] ={}  #必须得先把节点加上,再在下面进行一个参数配置,否则会报错
config['bitbucket.org']['User'] = 'hg' #增加一个配置

#换种写法
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com'] #先把一个节点赋给一个变量也是OK的
topsecret["Host Port"] = '50022'


config['DEFAULT']['ForwardX11'] = 'yes' #默认节点也可以这样搞

#将写好的配置文件写入文件
with open('example.ini','w') as configfile:
    config.write(configfile)

3、读取一个配置文件

RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的解析。
read(filename) 直接读取ini文件内容
sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option
items(section) 得到该section的所有键值对
get(section,option) 得到section中option的值,返回为string类型
getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

# [DEFAULT]
# compressionlevel = 9
# compression = yes
# serveraliveinterval = 45
# forwardx11 = yes
# 
# [hello.org]
# ip = 192.168.9.12
# serveraliveinterval = 46
# 
# [bitbucket.org]
# serveraliveinterval = 46
# 
# [portal]
# url = http://%(host)s:%(port)s/Portal
# host = localhost
# port = 8888
# 
# [topsecret.server.com]
# host port = 50022

import configparser
config = configparser.ConfigParser()  #生成一个对象
config.read("example.ini") #这样就把配置文件读过来了

print(config.sections())  #打印一下节点,发现木有DEFAULT:['bitbucket.org', 'topsecret.server.com']

#打印某个节点下的键,会把DEFALUT的也打印一下,除非这个节点下的键将DEFAULT的值覆盖掉
print(config.options('bitbucket.org'))

#将某个节点的配置以键值对的形式打印出来,是一个list
print(type(config.items('bitbucket.org')) )

#获取某个单个键的值
print(config.get('bitbucket.org','user'))
print(config.get('bitbucket.org','compression')) #也可以获取默认的,如果没有覆盖的话

print("key:",config.items('bitbucket.org')[0][0],"value:",config.items('bitbucket.org')[0][1])
print(config.get('portal','url')) #明显支持%(value)s的解析,挺好用的

4、配置文件的删和改

import configparser
config = configparser.ConfigParser()  #生成一个对象

config.read('example.ini')


config.remove_section('section1')
config.remove_option('bitbucket.org','user')


config.set('portal','port','8888')

config.write(open('example.ini', "w"))

 

posted @ 2017-02-24 10:34  skiler  阅读(535)  评论(0编辑  收藏  举报