python读写配置文件操作

本文详细介绍使用Python的configparser模块进行配置文件的读写操作,包括如何添加、读取和删除配置项,以及处理不同数据类型的配置值。

1.简介 
- read(filename) 读取ini文件内容 
- sections() 以列表形式展示所有的section 
- options(section) 展示该section的option 
- items(section) 得到该section的所有键值对 
- get(section,option) 得到section中option的值,返回为string类型 
- getint(section,option) 得到section中option的值,返回int类型,还有相应的getboolean()和getfloat()函数。 
2.动态写入配置文件 
- add_section(section) 添加一个新的section 
- set(section,option,value) 新增section中的option 

def writeIni():
    # 第一步:创建conf对象
    conf = configparser.ConfigParser()
    # 第二步:添加section、options的值
    conf.add_section("path")
    conf.set("path", "back_dir", "/Users/abc/PycharmProjects/Pythoncoding/projects/")  # option
    conf.set("path", "target_dir", "/Users/abc/PycharmProjects/Pythoncoding/")  # option
    conf.add_section("file")
    conf.set("file", "back_file", "apitest")
    conf.set("file", "num", "10")
    # 第三步:写入文件
    with open("path.ini", 'w')as conffile:
        conf.write(conffile)

执行以上代码,写入配置文件,生成一个path.ini配置文件:

[path]
back_dir = /Users/abc/PycharmProjects/Pythoncoding/projects/
target_dir = /Users/abc/PycharmProjects/Pythoncoding/

[file]
back_file = apitest
num = 10

读取配置文件:

def readIni():
    config = configparser.ConfigParser()
    # 第四步:读取配置文件中的section、options的值
    # config.read_file(open('path.ini'))
    # 一开始是用上面的read_file读取配置文件的,但是配置文件里有中文
    # 读取了之后出现编码问题,运行出错,故用下面的read函数读取
    config.read('path.ini', encoding='UTF-8')
    back_dir = config.get('path', 'back_dir')
    back_file = config.get("file", "back_file")
    num = config.get("file", "num")
    target_dir = config.get("path", "target_dir")

    l1 = config.sections()

    print("back_dir = %s" % back_dir)
    print("back_file = %s" % back_file)
    print("num = %s" % num)
    print("target_dir = %s" % target_dir)

    print("l1 = %s" % l1)

    i = config.getint("file", "num")

    print("i = %s" % i)

    l2 = config.options("file")
    print("l2 = %s" % l2)

    l3 = config.items("file")
    print("l3 = %s" % l3)

    """ 输出如下:
    back_dir = /Users/abc/PycharmProjects/Pythoncoding/projects/
    back_file = apitest
    num = 10
    target_dir = /Users/abc/PycharmProjects/Pythoncoding/
    l1 = ['path', 'file']
    i = 10
    l2 = ['back_file', 'num']
    l3 = [('back_file', 'apitest'), ('num', '10')]
    """

删除section和option操作操作:

def remove_section():
    conf_path = "path.ini"
    config = configparser.ConfigParser()
    config.read(conf_path, encoding='UTF-8')
    # 删除section是section1里md5选项
    config.remove_option('section1', 'md5')
    # 删除section是section2里所有选项
    config.remove_section('section2')
    # 删除后必须写入文件才有效
    with open(conf_path, 'w', encoding="UTF-8")as file:
        config.write(file)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值