python config_python修改config

本文介绍了如何使用Python的ConfigParser模块来管理和修改配置文件。通过安装`configparser`库,可以读取和写入配置文件的各个部分,包括获取和修改不同段落的参数值,以及添加新的段落。示例代码展示了读取配置文件,获取各段信息,以及更新和保存配置文件的操作。

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

安装

pip install configparser

config

[sensor]

light = 332

temperature = 13

humidity = 42

mq2 = 17

mq9 = 60

[sensor2]

new_key = new_value

代码

import os

from configparser import ConfigParser

conf_path = "config.ini" #配置文件路径

config = ConfigParser()

config.read(conf_path, encoding="utf-8")

#config_data.get('account', 'user_id')

#获取总共多少段

secs=config.sections()

print(secs)

#['sensor']

#获取某一段总共多少参数,不包含数据

opt=config.options('sensor')

print(opt)

#['light', 'temperature', 'humidity', 'mq2', 'mq9']

#获取某一段总共多少参数,包含数据

itm=config.items('sensor')

print(itm)

#[('light', '33'), ('temperature', '28'), ('humidity', '42'), ('mq2', '17'), ('mq9', '60')]

#获取某一段的某个参数 获取str类型和int类型

str_val = config.get("sensor", "light")

print(str_val)

int_val = config.getint("sensor", "temperature")

print(int_val)

#修改数据

config.set("sensor", "light", "332") #使用set直接修改指定字段值

config.set("sensor", "temperature", "13") #使用set直接修改指定字段值

#添加一个段落

config.add_section('sensor2')

config.set('sensor2', 'new_key', 'new_value')

#保存修改

with open(conf_path, "w") as fw:

config.write(fw) # 使用write将修改内容写到文件中,替换原来config文件中内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值