熱線電話:13121318867

登錄
首頁精彩閱讀python解析模塊(ConfigParser)使用方法
python解析模塊(ConfigParser)使用方法
2018-06-04
收藏

python解析模塊(ConfigParser)使用方法

很多軟件都有配置文件,今天介紹一下python ConfigParser模塊解析配置文件的使用方法

測試配置文件test.conf內容如下:

代碼如下:
[first]
w = 2
v: 3
c =11-3

[second]

sw=4
test: hello

測試配置文件中有兩個區域,first和second,另外故意添加一些空格、換行。

下面解析:

代碼如下:
>>> import ConfigParser
>>> conf=ConfigParser.ConfigParser()
>>> conf.read('test.conf')
['test.conf']
>>> conf.sections()   #獲得所有區域
['first', 'second']
>>> for sn in conf.sections():
...     print conf.options(sn)       #打印出每個區域的所有屬性
...
['w', 'v', 'c']
['sw', 'test']

獲得每個區域的屬性值:

代碼如下:
for sn in conf.sections():
    print sn,'-->'
    for attr in conf.options(sn):
        print attr,'=',conf.get(sn,attr)

輸出:

代碼如下:
first -->
w = 2
v = 3
c = 11-3
second -->
sw = 4
test = hello

好了,以上就是基本的使用過程,下面是動態的寫入配置,

代碼如下:
cfd=open('test2.ini','w')
conf=ConfigParser.ConfigParser()
conf.add_section('test')         #add a section
conf.set('test','run','false')  
conf.set('test','set',1)
conf.write(cfd)
cfd.close()

上面是向test2.ini寫入配置信息。


數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢