安裝
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文件中內容
