configparser模块
1.用python创建config.ini文件:
1 #__author__ = jin 2 #__date__ = 2018-07-17 3 import configparser 4 config = configparser.ConfigParser() 5 6 config["DEFAULT"] = {"ServerAliveInterval":"45", 7 "Compression":"yes", 8 "ConpressionLevel":"9"} 9 config["bitbucket.org"] = {"User":"hg"} 10 11 with open("config.ini","w") as configfile: 12 config.write(configfile)
运行结果为:
生成config.ini文件:
2.在上述文件中增加一个section:
import configparser config = configparser.ConfigParser() config.read("config.ini") config.add_section("topsecret.server.com") #config.remove_section()为删除section
config.add_section("topsecret.server.com")
config.write(open("config.ini","w"))
运行结果:
3.在上述文件中增加的section中增加一组值:
import configparser config = configparser.ConfigParser() config.read("config.ini") config.set("topsecret.server.com","user","jin") config.write(open("config.ini","w"))
运行结果:
相反的删除为:
import configparser config = configparser.ConfigParser() config.read("config.ini") config.remove_option("topsecret.server.com","user") config.write(open("config.ini","w"))
运行结果为:
4.其它:
config.get(section,optopn) #取值 config.items("bitbucket.org")#取此section下的key和value