1. 程式人生 > >python模組之configparser

python模組之configparser

此模組用於生成和修改常見配置文件,當前模組的名稱在 python 3.x 版本中變更為 configparser。

解析下面的檔案格式:

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

[bitbucket.org]
User = hg

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

 

解析配置檔案

import configparser

conf = configparser.ConfigParser()  #
例項化(生成物件) # print(conf.sections()) #呼叫sections方法 [] conf.read('conf.ini') # 讀配置檔案(注意檔案路徑) print(conf.sections()) # 呼叫sections方法(預設不會讀取default #['bitbucket.org', 'topsecret.server.com'] print(conf.default_section) # ['bitbucket.org', 'topsecret.server.com'] # print(conf['bitbucket.org']['User']) # hg
for key, value in conf['bitbucket.org'].items(): print(key, value) # 每個節點會有預設有DEFAULT的引數 ''' user hg serveraliveinterval 45 compression yes compressionlevel 9 forwardx11 yes ''' if 'user' in conf['bitbucket.org']: print('True')

增刪改查
#

conf = configparser.ConfigParser()

conf.read(
'conf2.ini') # print(conf.options('group1')) # 拿到key print(conf['group1']['k2']) # v2 拿到value print(conf.has_option('group1', 'key1')) # False # conf.add_section('group3') conf['group3']['name'] = 'Alex Li' conf['group3']['age'] = '22' conf.write(open('conf3.ini', 'w')) ''' [group1] k1 = v1 k2 = v2 [group2] k1 = v1 [group3] name = Alex Li age = 22 ''' # conf.remove_option('group1', 'k2') conf.remove_section('group1') # 把整個group1和裡面的內容全刪了 conf.write(open('conf4.ini', 'w')) # conf['group1']['k1'] = 'haha' conf.write(open('conf2.ini', 'w'))