转自:https://www.cnblogs.com/luo25236240/p/9261882.html
1.基本的读取配置文件
-read(filename) 直接读取文件内容 (windows 下的 .conf 及 .ini 文件等)
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
2.基础写入配置文件
-set( section, option, value 对section中的option进行设置,需要调用write将内容写入配置文件
-remove_section(section) 删除某个 section
-remove_option(section, option) 删除某个 section 下的 option
转载:https://blog.csdn.net/miner_k/article/details/77857292
1 #encoding=utf-8 2 import ConfigParser 3 cf = ConfigParser.ConfigParser() 4 5 cf.read("e:\myapp.conf") 6 7 secs = cf.sections() 8 print secs 9 print type(secs) 10 print "-------->" 11 opts = cf.options("db") 12 print opts 13 print type(opts) 14 print "----->" 15 16 kvs = cf.items("db") 17 print kvs 18 print type(kvs) 19 print dict(kvs) 20 print "------->" 21 22 kl=cf.get("db","port") 23 print kl 24 print type(kl) 25 print "------------>" 26 ki=cf.getint("db","port") 27 print ki 28 print type(ki) 29 30 print "111------------>" 31 32 33 #cf.write("aa.init") 34 cf.set("db", "b_key3", "new-$r") 35 cf.set("db", "b_newkey", "new-value") 36 37 #保存配置,set、 remove_option、 add_section 和 remove_section 等操作并不会修改配置文件,write 方法可以将 ConfigParser 对象的配置写到文件中 38 cf.add_section('a_new_section') 39 cf.set('a_new_section', 'new_key', 'new_value') 40 41 cf.write(open("myapp1.conf", "w")) 42 43 #cf.write(sys.stdout)
['db', 'ssh', 'sad']
-------->
['host', 'port', 'user', 'pass']
----->
[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('pass', 'root23')]
{'host': '127.0.0.1', 'pass': 'root23', 'port': '3306', 'user': 'root'}
------->
3306
------------>
3306
111------------>
Process finished with exit code 0
myapp1.conf
[db]
host = 127.0.0.1
port = 3306
user = root
pass = root23
b_key3 = new-$r
b_newkey = new-value
[ssh]
host = 192.168.1.101
user = huey
pass = huey
port = 3306
myapp1.conf
[db]
host = 127.0.0.1
port = 3306
user = root
pass = root23
b_key3 = new-$r
b_newkey = new-value
[ssh]
host = 192.168.1.101
user = huey
pass = huey
port = 3306
[sad]
[a_new_section]
new_key = new_value