手机
当前位置:查字典教程网 >脚本专栏 >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装饰器验证配置文件示例

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

python批量下载图片的三种方法

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

python中使用sys模板和logging模块获取行号和函数名的方法

python使用ctypes模块调用windowsapi获取系统版本示例

python中使用smtplib和email模块发送邮件实例

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

python使用paramiko模块实现ssh远程登陆上传文件并执行

让python的Cookie.py模块支持冒号做key的方法

精品推荐
分类导航