手机
当前位置:查字典教程网 >脚本专栏 >python >Python使用自带的ConfigParser模块读写ini配置文件
Python使用自带的ConfigParser模块读写ini配置文件
摘要:在用Python做开发的时候经常会用到数据库或者其他需要动态配置的东西,硬编码在里面每次去改会很麻烦。Python自带有读取配置文件的模块C...

在用Python做开发的时候经常会用到数据库或者其他需要动态配置的东西,硬编码在里面每次去改会很麻烦。Python自带有读取配置文件的模块ConfigParser,使用起来非常方便。

ini文件

ini配置文件格式:

Python使用自带的ConfigParser模块读写ini配置文件1

读取配置文件:

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使用自带的ConfigParser模块读写ini配置文件2

【Python使用自带的ConfigParser模块读写ini配置文件】相关文章:

用python代码做configure文件

python实现的解析crontab配置文件代码

使用python装饰器验证配置文件示例

python用ConfigObj读写配置文件的实现代码

python使用在线API查询IP对应的地理位置信息实例

python代码制作configure文件示例

Python模块学习 filecmp 文件比较

python解析模块(ConfigParser)使用方法

Python中使用中文的方法

python读写文件操作示例程序

精品推荐
分类导航