配置文件configparser

1.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类型
 

1.2.写入配置文件

-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置
  xx.write(open("filename","w"))  需要调用write将内容写入配置文件。

[Your Choice]
alex = aaaaaaaaaa
xxxx = aaa
bbbb = 1234
dasdsqdq = aaa

[Your age]
alex = 22

[Your hobby]
play = football
View Code
import configparser
c=configparser.ConfigParser()
c.read("test.conf")
a=c.sections()
print(a)    #['Your Choice', 'Your age']
a=c.items("Your Choice")
print(a)    #[('alex', '1234'), ('xxxx', 'aaa'), ('bbbb', '1234'), ('dasdsqdq', 'aaa')]
a=c.get("Your Choice","alex")
print(a)    #1234    返回String类型
a=c.getint("Your age","alex")
print(a)    #22  返回int类型
c.set("Your Choice","alex","aaaaaaaaaa")
c.add_section("Your hobby")     #添加新的section
c.set("Your hobby","play","football")
c.write(open("test.conf","w"))
原文地址:https://www.cnblogs.com/arthas-zht/p/6550053.html