生成文件
import configparser
config = configparser.ConfigParser()
#在DEFAULT節點下添加,類似字典的key和value
config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}
config['bitbucket.org'] = {"alex":33}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes' #在在DEFAULT節點下添加key爲'ForwardX11,value爲yes的數據
with open('example.ini', 'w') as configfile:
config.write(configfile)
[DEFAULT] 創建文件的內容
#serveraliveinterval = 45
#compression = yes
#compressionlevel = 9
#forwardx11 = yes
#[bitbucket.org]
#alex = 33
#user = hg
#[topsecret.server.com]
#host port = 50022
#forwardx11 = no
configparser文件讀取寫入
import configparser
conf=configparser.ConfigParser()
conf.read("example.ini")
print(conf.sections())#打印節點(除了“DEFAULT”以外的節點)
print(conf["bitbucket.org"]["user"])
print(conf.defaults())#打印[DEFAULT]
#刪除後,創建新文件寫入
#sec = conf.remove_section('bitbucket.org')
#conf .write(open('exmple.cfg', "w"))
#刪除後,覆蓋原文件
#sec = conf.remove_section('bitbucket.org')
#conf .write(open('exmple.ini', "w"))