python conf配置文件

#为什么要做配置文件:
#将所有的代码和配置都变成模块化可配置化,这样就提高了代码的重用性,不用都去修改代码内部,这个就是我们逐步
#要做的事情,可配置化
#configparser用法
#1)创建configparser对象,并调用read()函数打开配置文件,里面填的参数是地址
#2)配置文件的格式是[]包含的是section,section下有option=value这样的键值对
'''


3.依据section来读取相应的配置数据 读 写
'''


#1.创建configparser对象
import configparser
cf=configparser.ConfigParser()
#2.从配置文件中读取数据
import os
cf.read(os.getcwd()+"/config.conf")
#读取所有section
print(cf.sections())       #返回列表形式    ['mysql_info', 'test_addSection']
#读取section下的option
print(cf.options(section="mysql_info"))  #只有key值 ['mysql_host', 'mysql_port', 'mysql_db', 'mysql_user', 'mysql_passwd']
#读取键值对
print(cf.items(section="mysql_info"))   #键值对 [('mysql_host', '120.76.42.189'), ('mysql_port', '3306'), ('mysql_db', 'future'), ('mysql_user', 'futurevistor'), ('mysql_passwd', '123456')]
#读section里option
print(cf.get("mysql_info","mysql_db"))     #future
print(cf.getint("mysql_info","mysql_port")) #3306

#写
#添加option,修改也用set
cf.set("mysql_info","type","mysql5.7")
#添加section
cf.add_section("test")
cf.set("test","sex","female")
#添加完option section后都要打开文件写入
with open(os.getcwd()+"/config.conf","w") as cfile:
    cf.write(cfile)  #文件流写到文件中去

 

posted on 2018-03-25 16:16  一枚快乐的小测试  阅读(6262)  评论(0编辑  收藏  举报