前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python ConfigParser模

python ConfigParser模

作者头像
py3study
发布2020-01-07 16:22:34
5080
发布2020-01-07 16:22:34
举报
文章被收录于专栏:python3

主文件:

from ConfigParser import ConfigParser

config = ConfigParser()

config.read("test.xml")

函数使用:

1.读取配置文件

-read(filename) 直接读取ini文件内容

-sections() 得到所有的section,并以列表的形式返回

-options(section) 得到该section的所有option

-items(section) 得到该section的所有键值对

-get(section,option) 得到section中option的值,返回为string类型

-getint(section,option) 得到section中option的值,返回为int类型

2.写入配置文件

-add_section(section) 添加一个新的section

-set( section, option, value) 对section中的option进行设置

config.write(open('test.xml','w'))

         需要调用write将内容写入配置文件。

3.例子

代码语言:javascript
复制
import ConfigParser   import string, os, sys   cf = ConfigParser.ConfigParser()   cf.read("test.conf")   # 返回所有的section   s = cf.sections()   print 'section:', s   o = cf.options("db")   print 'options:', o   v = cf.items("db")   print 'db:', v   print '-'*60   #可以按照类型读取出来   db_host = cf.get("db", "db_host")   db_port = cf.getint("db", "db_port")   db_user = cf.get("db", "db_user")   db_pass = cf.get("db", "db_pass")   # 返回的是整型的   threads = cf.getint("concurrent", "thread")   processors = cf.getint("concurrent", "processor")   print "db_host:", db_host   print "db_port:", db_port   print "db_user:", db_user   print "db_pass:", db_pass   print "thread:", threads   print "processor:", processors   #修改一个值,再写回去   cf.set("db", "db_pass", "zhaowei")   cf.write(open("test.conf", "w"))  
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档