广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python ConfigParser模
  • 245
分享到

python ConfigParser模

pythonConfigParser 2023-01-31 06:01:05 245人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

主文件: from ConfigParser import ConfigParser config = ConfigParser() config.read("test.xml")   函数使用: 1.读取配置文件 -read(filena

主文件:

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.例子
  1. import ConfigParser   
  2. import string, os, sys   
  3. cf = ConfigParser.ConfigParser()   
  4. cf.read("test.conf")   
  5. # 返回所有的section   
  6. s = cf.sections()   
  7. print 'section:', s   
  8. o = cf.options("db")   
  9. print 'options:', o   
  10. v = cf.items("db")   
  11. print 'db:', v   
  12. print '-'*60   
  13. #可以按照类型读取出来   
  14. db_host = cf.get("db", "db_host")   
  15. db_port = cf.getint("db", "db_port")   
  16. db_user = cf.get("db", "db_user")   
  17. db_pass = cf.get("db", "db_pass")   
  18. # 返回的是整型的   
  19. threads = cf.getint("concurrent", "thread")   
  20. processors = cf.getint("concurrent", "processor")   
  21. print "db_host:", db_host   
  22. print "db_port:", db_port   
  23. print "db_user:", db_user   
  24. print "db_pass:", db_pass   
  25. print "thread:", threads   
  26. print "processor:", processors   
  27. #修改一个值,再写回去   
  28. cf.set("db", "db_pass", "zhaowei")   
  29. cf.write(open("test.conf", "w"))  

--结束END--

本文标题: python ConfigParser模

本文链接: https://www.lsjlt.com/news/190008.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作