温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中ConfigParser模块如何使用

发布时间:2021-07-19 18:01:25 来源:亿速云 阅读:131 作者:Leah 栏目:编程语言

Python中ConfigParser模块如何使用,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在Python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍。

Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如:

[db]  db_host=127.0.0.1  db_port=3306 db_user=root db_pass=password [concurrent]  thread=10 processor=20

假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:

#-*- encoding: gb2312 -*-  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"))

关于Python中ConfigParser模块如何使用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI