import configparser """ “[ ]”包含的为 section,section 下面为类似于 key - value 的配置内容; configparser 默认支持 ‘=’ ‘:’ 两种分隔。 ConfigParser模块在python3中修改为configparser.这个模块定义了一个ConfigParser类, 该类的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同.conf """ #初始化实例 config = configparser.ConfigParser() #注意大小写 #先要读取配置文件 config.read("test.ini") # 获取所有的sections config.sections() # 返回值为列表['test1', 'test2', 'test3'] ,会过滤掉 ["DEFAULT"] # 获取指定section的key value (注意key会全部变为小写,而value不会) config.items('test1') # [('money', '100'), ('name', 'WangFuGui'), ('age', '20')] # 获取指定section的keys name变为小写 config.options("test1") # ['name', 'age', 'money'] # 获取指定的key的value name 大小写均可以 value默认为字符 config["test1"]["Name"] # WangFuGui config.get("test1","name") # WangFuGui config.getint("test1","age") # 100 转换为int 类型 # 检查 "DEFAULT" in config # True "100"in config["test1"]["money"] # True # 添加 if "add_section1" not in config: config.add_section("add_section1") config.set("add_section1","hobby","game") #用set方法 config.write(open("test.ini","w")) # 一定要写入才生效 # 移除 config.remove_option("add_section1","hobby") config.remove_section("add_section1") config.write(open('test.ini',"w")) # 一定要写入才生效