[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.sections() #调用sections方法
[]
>>> config.read('example.ini') # 读配置文件(注意文件路径)
['example.ini']
>>> config.sections() #调用sections方法(默认不会读取default)
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config #判断元素是否在sections列表内
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) # for循环 bitbucket.org 字典的key,注意,DEFAULT中的也会出来,因为DEFAULT中的配置信息默认就是给下面的模块中的内容使用的
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
[group1] # 支持的两种分隔符“=”, “:”
k1 = v1
k2:v2
[group2]
k1 = v1
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read('i.cfg')
['i.cfg']
# ########## 读 ##########
>>> 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
>>>val = config.getint('group1','key')
# ########## 改写 ##########
>>>sec = config.remove_section('group1') # 删除section 并返回状态(true, false)
>>> print(sec)
True
>>>config.write(open('i.cfg', "w")) # 对应的删除操作要写入文件才会生效
>>>sec = config.has_section('vita')
>>> print(sec)
False
>>>sec = config.add_section('vita')
>>>config.write(open('i.cfg', "w")) #
查看内容
[group2]
k1 = v1
[vita]
>>>config.set('group2','k1',"11111")
>>>config.set('group2','k1',"2222")
>>>config.write(open('i.cfg', "w"))
查看内容
[group2]
k1 = 11111
k2 = 222
[vita]
>>>config.remove_option('group2','age')
>>>config.write(open('i.cfg', "w"))
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。