python读写ini文件

给你一囗甜甜゛ 提交于 2019-11-30 16:18:33

python来读写ini的配置文件

读取文件:

 

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)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!