一般的なドキュメント形式のソフトウェアの多くを見て、次のとおりです。
[DEFAULT]
ServerAliveInterval = 45
圧縮= yesの
がCompressionLevel = 9
ForwardX11 = yesの
[bitbucket.org]
ユーザー= HG
[topsecret.server.com]
ポート= 50022
ForwardX11 =なし
あなたのpythonで、このような文書を作成したい場合はどのようにそれを行うには?
インポートのConfigParserの
コンフィグ= configparser.ConfigParser()
コンフィグ[ "DEFAULT"] = { 'ServerAliveInterval': '45'、
'圧縮': 'はい'、
'がCompressionLevel': '9'}
コンフィグ[ 'bitbucket.org'] = {}
コンフィグ[ 'bitbucket.org'] [ 'ユーザ'] = 'HG'
コンフィグ[ 'topsecret.server.com'] = {}
topsecret = configの[ 'topsecret.server.com']
topsecret [ 'ホストポート' ] = '50022' #は、パーサ変異する
topsecret [ 'ForwardX11'] = 'NO' #ここで同じ
設定[ 'DEFAULT'] [ 'ForwardX11'] = 'yes'に<BR>
オープンで( 'example.ini'、 'をconfigfileをとしてW '):
config.write(configfileを)
CRUD
輸入のConfigParser
設定= configparser.ConfigParser()
#---------------------------------------- -----查
プリント(config.sections())#[]
config.read( 'example.ini')
プリント(config.sections())#[ 'bitbucket.org'、 'topsecret.server.com' ]
プリント( 'bytebong.com' configに)#偽
プリント(設定[ 'bitbucket.org'] [ 'ユーザー'])#のHGの
印刷(設定[ 'DEFAULT'] [ '圧縮が'])#yes
プリントを(コンフィグ[ 'topsecret.server.com'] [ 'forwardX11'])#NO
設定におけるキーの[ 'bitbucket.org']:
プリント(キー)
#ユーザ
#serveraliveintervalの
#圧縮
#がCompressionLevel
#forwardx11
プリント(config.options( 'bitbucket.org'))#1 [ 'ユーザ'、 'serveraliveinterval'、 '圧縮'、 'がCompressionLevel'、 'forwardx11']
プリント(config.items( 'bitbucket.org'))#[ ( 'serveraliveinterval'、 '45')、( '圧縮'、 'はい')、( 'がCompressionLevel'、 '9')、( 'forwardx11'、 'はい')、( 'ユーザ'、 'HGを')]
印刷(config.get( 'bitbucket.org'、 '圧縮'))#はい
#------------------------------ ---------------删、改、增(config.write(オープン( 'i.cfg'、 "W")))
config.add_section( '元')
config.remove_section ( 'topsecret.server.com')
config.remove_option( 'bitbucket.org'、 'ユーザ')
config.set( 'bitbucket.org'、'K1'、 '11111')
config.write(オープン( 'i.cfg'、 "W"))
原文链接:https://www.cnblogs.com/yuanchenqi/articles/5732581.html