import configparser
TestIniFile = "config.ini"
ReadwriteSection = "Section5"
def Inidemotest():
# 读取
cf = configparser.ConfigParser()
cf.read(TestIniFile)
print(cf)
print("--------------------------------")
# 获得所有section
secs = cf.sections()
print("sections:", secs)
print("--------------------------------")
for s in secs:
opts = cf.options(s)
print("current section key:", s)
print(opts)
print("--------------------------------")
for s in secs:
items = cf.items(s)
print("current section:", s)
for i in items:
print(i)
print("--------------------------------")
for s in secs:
opts = cf.options(s)
for o in opts:
val = cf.get(s, o)
print(s, o, val, type(val))
print("--------------------------------")
# 增加
cf.add_section(ReadwriteSection)
cf.set(ReadwriteSection, "new_key", "new_value")
# 写入
cf.write(open(TestIniFile, "w"))
# 判断是否有section
ret = cf.has_section(ReadwriteSection)
print(ret) # True
# 删除
cf.remove_section(ReadwriteSection)
# 判断是否有section
ret = cf.has_section(ReadwriteSection)
print(ret) # False
# 写入
cf.write(open(TestIniFile, "w"))
if __name__ == '__main__':
Inidemotest()
[Section1]
home1 = hometwon_gd1
home11 = hometwon_gd11
[Section2]
tel2 = 010-21232435
tel22 = 020-2353445756867
[Section3]
url3 = https:
url33 = http:
[Section4]
num4 = 123456
num44 = 98765