import configparser config = configparser.ConfigParser(allow_no_value=True) config.read("test.ini") ''' ============test.ini============= [db] host = 127.0.0.1 port = 8888 user = root password = toor [hosts] 192.168.1.1 192.168.1.2 192.168.1.3 [mysql_new] ip1 = 1.1.1.1 ip2 = 2.2.2.2 [mytest1] 192.168.1.1 ''' #查看对应的section print(config.sections()) #查看指定section里面的host对应的值 print(config.get("db","host")) # for name,value in config.items("db"): print(f"{name}={value}") #新增一个section config.add_section("mysql_new") #给指定的section里新增配置 config.set("mysql_new","ip1","1.1.1.1") config.set("mysql_new","ip2","2.2.2.2") #变动后需要写保存 config.write(open(file=r'test.ini',mode='w')) #判断是否存在指定的section和option是否存在 if not config.has_section("mytest1"): config.add_section("mytest1") print("创建mytest1 section") if not config.has_option("mytest1","192.168.1.1"): config.set("mytest1","192.168.1.1") print("给mytest1 section添加了192.168.1.1 option") config.write(open(file=r'test.ini',mode='w'))