pythonプロファイル、iniファイル、configparserの変更

12051 ワード

文書ディレクトリ
まず使用するパッケージはconfigparserで、インストール:
pip install configparser

多くのパートナーが問題に直面しているのは、configparserがiniプロファイルに要求していることです.あるiniファイルには[default],[secation 1]など[***]という言葉がありません.実はこれはiniファイルのヘッダで、すべてがなければエラーを報告します.以下のエラーです.
MissingSectionHeaderError: File contains no section headers.

では、もしなかったら、自分で追加して、具体的にiniファイルをどのように分類するかは、個人次第です.paramsがあるiniのプロファイル、内容は以下の通りです.
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

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

ここには全部で3つのsection、すなわち3つの中かっこがあるので、このiniは3つのクラスに分けられています.では、ある値を読み取るにはコマンドで読みます.
import configparser
config = configparser.ConfigParser()

paramsを読み込む.iniファイルには、次のような出力があります.
In [6]: config.read('params.ini')
Out[6]: ['params.ini']

ローの値を読み込みたい場合は、ローの値を変更し、ローを追加してローの値を削除します.
##########################################################
#         :
In [8]: config['DEFAULT']['ServerAliveInterval']
Out[8]: '45'
In [10]: config['bitbucket.org']['User']
Out[10]: 'hg'
In [12]: config['topsecret.server.com']['Port']
Out[12]: '50022'
##########################################################
#         :
In [13]: config['DEFAULT']['ServerAliveInterval'] = '46'
In [14]: config['topsecret.server.com']['Port'] = 'jf'
In [15]: config['bitbucket.org']['User'] = '20000'
#      :
In [17]: config['DEFAULT']['ServerAliveInterval']
Out[17]: '46'
In [18]: config['topsecret.server.com']['Port']
Out[18]: 'jf'
In [19]: config['bitbucket.org']['User']
Out[19]: '20000'
##########################################################
#     section:
In [20]: config.add_section('Section2')
#      section         :
In [21]: config.set('Section2', 'newKey1', 'newValue1')
#          section      :
In [22]: config.set('DEFAULT', 'newKey2', 'newValue2')
##########################################################
#      :
In [30]: config.remove_section('Section2')
Out[30]: True
In [34]: config.remove_option('DEFAULT','newKey2')
Out[34]: True
##########################################################
#     params.ini         ,        ,         ,       config.write('params.ini','w'),       
with open('params.ini', 'w') as configfile:
	config.write(configfile)
##########################################################