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'
))
|
输出: