python中配置文件的使用

一. 什么是配置文件?为什么要做配置文件?

将所有的代码和配置都变成模块化可配置化,这样就提高了代码的重用性,不再每次都去修改代码内部,这个就是我们逐步要做的事情,可配置化

 

二. python中的ConfigParser类

模块:from configparser import ConfigParser

 

configparser是Python自带的模块,用法如下:

1. 创建ConfigParser对象。并调用read()函数打开配置文件,里面填的参数是地址

2. 配置文件的格式是:[]包含的叫section,section下有option=value这样的键值

3. 常用配置函数如下

sections()  得到所有的section,并以列表的形式返回

options(section)  得到该section的所有option (key值)

items(section)  得到该section的所有键值对

get(section, option)  得到section中option的值,返回为string类型,指定标签下面的key对应的value值

getint(section, option)  得到section中的option值,返回为int类型

 

add_section()  往配置文件中添加section

set(section, name, value)  在section下设置name=value

with open(configfile) as cfile:

  write(cfile)

将新增的配置信息写入到文件中

 

三. 实例

1. 在lesson_config包下创建一个配置文件db.cfg和一个py文件config_operate.py

2. db.cfg的内容为

[mysql_db_test]
host=localhost
port=3306
db=mysql
user=root
passwd=123456

3. config_operate.py的内容为

from configparser import ConfigParser

#初始化类
cp = ConfigParser()
cp.read("db.cfg")

#得到所有的section,以列表的形式返回
section = cp.sections()[0]
print(section)

#得到该section的所有option
print(cp.options(section))

#得到该section的所有键值对
print(cp.items(section))

#得到该section中的option的值,返回为string类型
print(cp.get(section, "db"))

#得到该section中的option的值,返回为int类型
print(cp.getint(section, "port"))

运行结果

mysql_db_test
['host', 'port', 'db', 'user', 'passwd']
[('host', 'localhost'), ('port', '3306'), ('db', 'mysql'), ('user', 'root'), ('passwd', '123456')]
mysql
3306

 

转载于:https://www.cnblogs.com/my_captain/p/9294829.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值