#coding:utf-8
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("1.ini")
print config.sections()
print config.options("db")
print config.items("db")
print config.get("db", "dbuser")
print config.getint("db", "dbport")
for sections in config.sections():
for items in config.items(sections):
#打印单独键值对
print items
['db', 'emain']
['dbuser', 'dbpassword', 'dbport']
[('dbuser', 'test'), ('dbpassword', 'test'), ('dbport', '3308')]
test
3308
('dbuser', 'test')
('dbpassword', 'test')
('dbport', '3308')
('emailto', '***qq.com')
注意:在读取的时候传入的sections,options要实际存在,否则会报错。
配置文件内容如下:
[db]
dbuser = test
dbpassword = test
dbport = 3308
[emain]
emailto = ***qq.com
#coding:utf-8
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("1.ini")
config.add_section("user")
config.set("user", "name", "Edward")
if "db" not in config.sections():
config.add_section("db")
config.set("db","dbuser","platform")
with open("1.ini","w+") as f:
config.write(f)
运行之后配置文件:open函数知识点传送门——https://blog.csdn.net/weixin_43533825/article/details/87524543
在对section操作之前,要先判断section是否存在,否则会报错
[db]
dbuser = platform
dbpassword = test
dbport = 3308
[emain]
emailto = ***qq.com
[user]
name = Edward
如果config对象,没有进行read("1.ini")的情况:
[db]
dbuser = platform
dbpassword = test
dbport = 3308
[emain]
emailto = ***qq.com
#coding:utf-8
import ConfigParser
config = ConfigParser.ConfigParser()
config.add_section("user")
config.set("user", "name", "Edward")
if "db" not in config.sections():#这里sections是空
config.add_section("db")
config.set("db","dbuser","platform")
with open("1.ini","w+") as f:
config.write(f)
[user]
name = Edward
[db]
dbuser = platform
注意:操作section之前需要判断section是否存在,避免运行抛异常~