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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

j_hao104   2021-03-22 我要评论
想了解Python使用自带的ConfigParser模块读写ini配置文件的相关内容吗,j_hao104在本文为您仔细讲解Python使用ConfigParser模块读写ini的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,ConfigParser,ini,配置文件,下面大家一起来学习吧。

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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们