1. 程式人生 > >configparser解析配置文件

configparser解析配置文件

ESS ali lse items mov 生成 true rem .section

1.配置文件
[DEFAULT]
ServerAliveInterval = 45   
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

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

2.解析配置文件

>>> 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‘

3.其他增刪改查方法

 [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"))

configparser解析配置文件