python对ini文件操作

本文详细介绍了使用Python的ConfigParser模块读写ini配置文件的方法,包括读取配置、获取section、选项和值,以及动态添加、删除section并进行写入。重点展示了如何处理Section5部分的操作和验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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://blog.youkuaiyun.com/liulin1207/article/details/107002722/
url33 = http://www.myexceptions.net/other-database/201669.html

[Section4]
num4 = 123456
num44 = 98765


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值