python操作ini文件

 

'''python 操作 ini 文件
ini文件的特点,多个节(section),每个节下可以存储多个 k-v 值
'''
from configparser import ConfigParser

config = ConfigParser()

# 写ini文件
def wIni():
    config['zhangsan'] = {'name': '张三', 'age': 18}
    config['lisi'] = {'name': '李四', 'age': 19}

    with open('test.ini', 'w', encoding='utf-8')as f:
        config.write(f)

# 增加一个 section
def addSection():
    config.read('test.ini', encoding='utf-8')
    config.add_section('test')

# 增加一个 key
def addOption():
    config.read('test.ini', encoding='utf-8')
    config.set('zhangsan', 'sex', '男')

# 删除一个 section
def reSection():
    config.read('test.ini', encoding='utf-8')
    config.add_section('lisi')

# 删除一个 key
def reOption():
    config.read('test.ini', encoding='utf-8')
    config.remove_option('zhangsan', 'sex')

# 判断section是否在ini文件中
def isSection():
    config.read('test.ini', encoding='utf-8')
    print('zhangsan' in config)


# 查看所有 section
def rIniSections():
    config.read('test.ini', encoding='utf-8')
    sections = config.sections()
    print(sections)

# 查看 section 下所有 key
def rSectionKVs():
    config.read('test.ini', encoding='utf-8')
    sections = config.options('zhangsan')
    print(sections)

# 查看 section 下所有 k-v
def rSectionKVs():
    config.read('test.ini', encoding='utf-8')
    sections = config.items('zhangsan')
    print(sections)


# 查看 section 下 key 的 value
def rIniSectionKV():
    config.read('test.ini', encoding='utf-8')
    value = config.get('zhangsan', 'name')
    print(value)

 

上一篇:解决IAR编译出现Warning[25]: Label 'xxx' is defined pubweak in a section implicitly declared root


下一篇:C# 利用动态库DllImport("kernel32")读写ini文件