您好,登錄后才能下訂單哦!
[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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。