Home  >  Article  >  Backend Development  >  Python使用自带的ConfigParser模块读写ini配置文件

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

WBOY
WBOYOriginal
2016-07-06 13:29:471452browse

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

ini文件
ini配置文件格式:

2016626174140238.png (273×249)

读取配置文件:

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'))

输出:

2016626174242767.png (288×355)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn