Python中使用ConfigParser解析ini配置文件实例
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python中使用ConfigParser解析ini配置文件实例,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2232字,纯文字阅读大概需要4分钟。
内容图文
![Python中使用ConfigParser解析ini配置文件实例](/upload/InfoBanner/zyjiaocheng/434/c8a7e999f44f4947b610ccfc43ea595f.jpg)
[Section1]
option1 : value1
option2 : value2
python提供了一个简单的模块ConfigParser可以用来解析类似这种形式的文件。对于ConfigParser模块可以解析key:value和key=value这样的类型,对于#和;开头的行将会自动忽视掉。相当于注释行。常用的函数:
ConfigParser.RawConfigParser()
RawConfigParser Object的操作有:
.sections() : 返回所有可用的section
.addsection(sectionname) :添加section
.set(sectionname, optionname, optionvalue): 添加option
.hassection(sectionname) :判断
.options(sectionname) : 返回section下可用的option
.hasoption(sectionname, optionname) : 判断
.read(filename) : 读取文件
.wrie(filename) : 将RawConfigParser对象写到文件中
.get(sectionname, optionname) : 获取值, 默认的是返回string类型
.getfloat, .getint, .getboolean : 获取不同类型的返回值,参数和get的参数一样
.items(sectionname) :列出section下的所有key:value
.remove(sectionname) :删除section
.remove(sectionname, option_name) : 删除section下的某个option
Demo -- 生成文件
$ cat ini_demo.py
# -*- coding:utf-8 -*-
import ConfigParser
def gen_ini():
ftest = open('test','w')
config_write = ConfigParser.RawConfigParser()
config_write.add_section('Section_a')
config_write.add_section('Section_b')
config_write.add_section('Section_c')
config_write.set('Section_a','option_a1','apple_a1')
config_write.set('Section_a','option_a2','banana_a2')
config_write.set('Section_b','option_b1','apple_b1')
config_write.set('Section_b','option_b2','banana_b2')
config_write.set('Section_c','option_c1','apple_c1')
config_write.set('Section_c','option_c2','banana_c2')
config_write.write(ftest)
ftest.close()
if __name__ == "__main__":
gen_ini()
最后生成的文件为:
$ cat test
[Section_a]
option_a1 = apple_a1
option_a2 = banana_a2
[Section_c]
option_c2 = banana_c2
option_c1 = apple_c1
[Section_b]
option_b1 = apple_b1
option_b2 = banana_b2
Demo -- 读取文件
def read_ini():
config_read = ConfigParser.RawConfigParser()
config_read.read('test')
print config_read.sections()
print config_read.items('Section_a')
print config_read.get('Section_a','option_a1')
最后的结果为:
['Section_a', 'Section_c', 'Section_b']
[('option_a2', 'banana_a2'), ('option_a1', 'apple_a1')]
apple_a1
内容总结
以上是互联网集市为您收集整理的Python中使用ConfigParser解析ini配置文件实例全部内容,希望文章能够帮你解决Python中使用ConfigParser解析ini配置文件实例所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。