手机
当前位置:查字典教程网 >脚本专栏 >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 tempfile模块学习笔记(临时文件)

通过python下载FTP上的文件夹的实现代码

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

在python中的socket模块使用代理实例

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

python使用pyhook监控键盘并实现切换歌曲的功能

python使用os模块的os.walk遍历文件夹示例

Python中os和shutil模块实用方法集锦

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

精品推荐
分类导航