首页 > 其他 > 详细

configparser模块

时间:2021-04-30 10:11:31      阅读:20      评论:0      收藏:0      [点我收藏+]
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‘))

  

configparser模块

原文:https://www.cnblogs.com/imdba/p/14720110.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!