http://www.jb51.net/article/87402.htm
需要注意的是每一個字段后面的值外面沒有引號,切記,自己第一次配置時,加了引號,搞了半天 沒找到錯誤,,
在用Python做開發的時候經常會用到數據庫或者其他需要動態配置的東西,硬編碼在里面每次去改會很麻煩。Python自帶有讀取配置文件的模塊ConfigParser,使用起來非常方便。
ini文件
ini配置文件格式:
讀取配置文件:
1
2
3
4
5
6
7
|
import
ConfigParser
conf
=
ConfigParser.ConfigParser()
conf.read(
'dbconf.ini'
)
# 文件路徑
name
=
conf.get(
"section1"
,
"name"
)
# 獲取指定section 的option值
print
name
sex
=
conf.get(
"section1"
,
"sex"
)
# 獲取section1 的sex值
print
age
|
輸出:
1
2
|
jhao
male
|
寫入配置文件:
1
2
3
4
5
6
7
8
9
|
import
ConfigParser
conf
=
ConfigParser.ConfigParser()
conf.read(
'dbconf.ini'
)
conf.
set
(
"section1"
,
"name"
,
"jhao104"
)
# 修改指定section 的option
conf.
set
(
"section1"
,
"age"
,
"21"
)
# 增加指定section 的option
conf.add_section(
"section3"
)
# 增加section
conf.
set
(
"section3"
,
"site"
,
"oschina.net"
)
# 給新增的section 寫入option
conf.write(
open
(
'dbconf.ini'
,
'w'
))
|
輸出: