python的配置解析模組ConfigParser

2022-07-24 04:12:14 字數 1349 閱讀 2507

很多軟體都有配置檔案,今天介紹並記錄一下configparser模組,解析配置檔案。

測試配置檔案test.conf內容如下: 

[first]

w = 2v: 3c =11-3[second]

sw=4test: 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 = 2v = 3c = 11-3second -->sw = 4test = hello

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

1 cfd=open('

test2.ini

','w')

2 conf=configparser.configparser()

3 conf.add_section('

test

') #add a section

4 conf.set('

test

','run

','false

')

5 conf.set('

test

','set

',1)

6conf.write(cfd)

7 cfd.close()

上面是向test2.ini寫入配置資訊。

Python解析模組argparse

初學python,今天在偶然間了解到python中有個解析模組argparse,其實此解析模組和linuxc下的getopt 的功能大同小異,寫此篇博文的目的只是為了做個筆記 熟悉linux系統命令的人都知道,每個命令後面都可以跟許多引數來實現不同的功能,拿最簡單的ls來舉例吧 當我們輸入ls是終端...

使用ConfigParser模組解析配置檔案

python提供了configparser模組來解析配置檔案,它解析的配置檔案格式類似於ini配置檔案,檔案被分成若干個section,每個section中有具體的配置資訊,例如 mysqld user mysql pid file var run mysqld mysqld.pid skip ex...

解析配置檔案ConfigParser模組

配置檔案內容 plain view plain copy db db host 127.0.0.1 db port 3306 db user root db pass password concurrent thread 10 processor 20 如果遵循以上格式,那麼就可以用python的c...