python读写ini文件
python来读写ini的配置文件
读取文件:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import configparser
cfp = configparser.ConfigParser()
cfp.read("test.ini")
'''获取所有的selections'''
selections = cfp.sections()
print(selections) # ['Title1', 'Title2']
'''获取指定selections下的所有options'''
options = cfp.options("Title1")
print(options) # ['key1', 'key2']
'''获取指定selection下的指定option的值'''
value= cfp.get("Title1", "key1")
print(value) # 1111111111
'''判断是否含有指定selection 或 option'''
print(cfp.has_section("Title1")) # True
print(cfp.has_option("Title1", "key3")) # False
写文件:
import configparser
cfp = configparser.ConfigParser()
cfp.read("test.ini")
cfp.add_section("Title3") # 设置option的值
cfp.set("Title3", "key1", "1111111111") # 注意这里的selection一定要先存在!
cfp.set("Title3", "key2", "2222222222")
cfp.remove_section("Title3") # 移除指定selection
cfp.remove_option("Title2", "key1") # 移除指定selection下的option
with open("test.ini", "w+") as f:
cfp.write(f)
本文来自博客园,作者:I'm_江河湖海,转载请注明原文链接:https://www.cnblogs.com/jhhh/p/16761923.html