Python内置模块ConfigParser实现配置读写功能的方法
Python  /  管理员 发布于 8年前   167
本文实例讲述了Python内置模块ConfigParser实现配置读写功能的方法。分享给大家供大家参考,具体如下:
用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。
#配置文件test.cfg[section1]k1 = v1k2 :v2k3 = 1[section2]k1 = v1
#coding:utf-8import ConfigParserconfig = ConfigParser.ConfigParser()config.read('test.cfg')# ########## 读 ###########获取所有sections.secs = config.sections()print secs #['section1', 'section2']#获取制定section的键keyoptions = config.options('section1')print options #['k1', 'k2', 'k3']#获取指定section的键值对key-valueitem_list = config.items('section1')print item_list #[('k1', 'v1'), ('k2', 'v2'), ('k3', '1')]#获取指定key的value# 获取字符串类型的valueval1 = config.get('section1','k1')# 获取整型的valueval2 = config.getint('section1','k3')# ########## 增改删 ########### 增加sectionif not config.has_section('section3'): config.add_section('section3') config.write(open('test.cfg', "w"))#设置optionif not config.has_section('section3'): config.set('section3','k1',11111) config.write(open('test.cfg', "w"))# 移除optionret = config.remove_option('section3','k1')print ret #True or Falseconfig.write(open('test.cfg', "w"))# 移除sectionret = config.remove_section('section3')print ret #True or Falseconfig.write(open('test.cfg', "w"))更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
test1 在
opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus中评论 test..122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..Zita 在
Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用中评论 111222..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
