美文网首页
模块 configparser

模块 configparser

作者: Rainy丶Wang | 来源:发表于2019-06-20 16:19 被阅读0次

python2下该模块名为ConfigParser,到3才改为configparser,可以看官方ConfigParser模块的说明
python3中configparser模块的使用,configparser模块是用来解析ini配置文件的解析器,关于ini配置文件的结构可以看python官方文档中的介绍:

ini文件结构需要注意一下几点:
键值对可用=或者:进行分隔
section的名字是区分大小写的,而key的名字是不区分大小写的
键值对中头部和尾部的空白符会被去掉
值可以为多行
配置文件可以包含注释,注释以#或者;为前缀

注意:configparser有default_section的概念,默认为[DEFAULT]节,也就是之后的所有的section都有该默认section中的键值对,详情参见configparser源码的init()方法

基本使用

为了创建如下ini文件:
configparser模块主要使用ConfigParser类来解析ini文件

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no

我们可以使用如下代码:

import configparser

config = configparser.ConfigParser()


config['DEFAULT'] = {
    'ServerAliveInterval': '45',
    'Compression':'yes',
    'CompressionLevel':'9',
    'ForwardX11':'yes',}

config['bitbucket'] = {}
config['bitbucket']['user'] = 'Rainy'

config['topsecret.server'] = {}
topsecret = config['topsecret.server']
topsecret['Port'] = '50022'
topsecret['ForwardX11'] = 'no'

with open('example.ini', 'w') as configfile:
    config.write(configfile)

然后我们再读取该ini文件:

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'

除了可以使用列表的方式获取值,也可以通过section级别的get()方法获取,同时该函数可以指定默认值

>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'

而解析器级别的get()函数的默认值是通过fallback参数指定的:

>>> config.get('bitbucket.org', 'monster',
...            fallback='No such things as monsters')
'No such things as monsters'

需要注意的是,无论是通过列表方式获取值,还是通过get()方法获取值,获取到的数据都字符串类型,如果想要获取指定类型的数据,可以使用如下的几个方法:

getint()
getfloat()
getboolean()
同时需要注意getboolean()方法能判断True/False的值有: ‘yes’/‘no’, ‘on’/‘off’, ‘true’/‘false’ 和 ‘1’/‘0’

增删改查

import configparser

config = configparser.ConfigParser()

#---------------------------------------------查
print(config.sections())   #[]

config.read('example.ini')

print(config.sections())   #['bitbucket.org', 'topsecret.server.com']

print('bytebong.com' in config)# False

print(config['bitbucket.org']['User']) # hg

print(config['DEFAULT']['Compression']) #yes

print(config['topsecret.server.com']['ForwardX11'])  #no


for key in config['bitbucket.org']:
    print(key)


# user
# serveraliveinterval
# compression
# compressionlevel
# forwardx11


print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
print(config.items('bitbucket.org'))  #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

print(config.get('bitbucket.org','compression'))#yes


#---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))


config.add_section('yuan')

config.remove_section('topsecret.server.com')
config.remove_option('bitbucket.org','user')

config.set('bitbucket.org','k1','11111')

config.write(open('i.cfg', "w"))

相关文章

网友评论

      本文标题:模块 configparser

      本文链接:https://www.haomeiwen.com/subject/xgrjqctx.html