Home > Backend Development > Python Tutorial > Python uses its own ConfigParser module to read and write ini configuration files

Python uses its own ConfigParser module to read and write ini configuration files

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

When developing in Python, databases or other things that require dynamic configuration are often used. It would be troublesome to hard-code them and change them every time. Python has its own module ConfigParser for reading configuration files, which is very convenient to use.

ini file
ini configuration file format:

2016626174140238.png (273×249)

Read configuration file:

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

Output:

jhao
male
Copy after login


Write configuration file:

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

Output:

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