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

WBOY
Release: 2016-07-06 13:29:47
Original
1451 people have browsed it

在用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

Copy after login

输出:

jhao
male
Copy after login


写入配置文件:

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

Copy after login

输出:

2016626174242767.png (288×355)

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!