python读conf配置文件_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) #文件流写到文件中去

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值