Python使用自带的ConfigParser模块读写ini配置文件
更新时间:2016年06月26日 17:48:59 作者:j_hao104
这篇文章主要介绍了Python使用自带的ConfigParser模块读写ini配置文件的方法,ConfigParser中包含了对ini的节section的一些基本操作,使得改写ini时非常简便,需要的朋友可以参考下
在用Python做开发的时候经常会用到数据库或者其他需要动态配置的东西,硬编码在里面每次去改会很麻烦。Python自带有读取配置文件的模块ConfigParser,使用起来非常方便。
ini文件
ini配置文件格式:
读取配置文件:
import ConfigParser conf = ConfigParser.ConfigParser() conf.read('dbconf.ini') # 文件路径 name = conf.get("section1", "name") # 获取指定section 的option值 print name sex = conf.get("section1", "sex") # 获取section1 的sex值 print age
输出:
jhao male
写入配置文件:
import ConfigParser conf = ConfigParser.ConfigParser() conf.read('dbconf.ini') conf.set("section1", "name", "jhao104") # 修改指定section 的option conf.set("section1", "age", "21") # 增加指定section 的option conf.add_section("section3") # 增加section conf.set("section3", "site", "oschina.net") # 给新增的section 写入option conf.write(open('dbconf.ini', 'w'))
输出:
相关文章
python中 conda 虚拟环境管理和jupyter内核管理
这篇文章主要介绍了python中 conda 虚拟环境管理和jupyter内核管理,文章基于pyhton以及conda的虚拟环境创建、删除、jupyter添加、删除虚拟kernel的方法,需要的朋友可以参考一下2022-04-04详解pyppeteer(python版puppeteer)基本使用
这篇文章主要介绍了详解pyppeteer(python版puppeteer)基本使用 ,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-06-06详谈python read readline readlines的区别
下面小编就为大家带来一篇详谈python read readline readlines的区别。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-09-09
最新评论