Python 之 ini 配置文件读取和写入

读取配置

config.ini

[select]
browser=Chrome
url=https://baidu.com

[mysql]
host=localhost
user=root
password=123456
port=3306
db=test

[config]
int_value=1
float_value=2.3
bool_value=False
import configparser

config_path = "./config.ini"
config = configparser.ConfigParser()
config.read(config_path)

print("\n===== 直接使用 section 和 key 读取 =====")
url = config["select"]["url"]
url = config.get("select", "url")
print(url)
# https://baidu.com

print("\n===== 获取所有 section =====")
# 如果提前不知道 section 有哪些,可以使用 config.sections() 获取可选的 section
sections = config.sections()
print(sections)
# ['select', 'mysql', 'config']

print("\n===== 获取 select 下的所有 key =====")
# 获取某个 section 下的所有 key
keys = config.options("select")
print(keys)
# ['browser', 'url']

print("\n===== 获取 select 下的所有 item =====")
items = config.items("select")
print(items)
# [('browser', 'Chrome'), ('url', 'https://baidu.com')]

print("\n===== 遍历获取每个 section 下每个 key 的 value =====")
for section in config.sections():
    print(f"[{section}]")
    for key in config.options(section):
        print(f"  {key}={config[section][key]}")
    # [select]
    #   browser=Chrome
    #   url=https://baidu.com
    # [mysql]
    #   host=localhost
    #   user=root
    #   password=123456
    #   port=3306
    #   db=test
    # [config]
    #   int_value=1
    #   float_value=2.3
    #   bool_value=False

print("\n===== 按指定类型获取配置信息 =====")
# 默认读取到的数据全部是str类型
value = config.get("config", "int_value")
print(type(value))  # <class 'str'>
value = config.getint("config", "int_value")
print(type(value))  # <class 'int'>
value = config.getfloat("config", "float_value")
print(type(value))  # <class 'float'>
value = config.getboolean("config", "bool_value")
print(type(value))  # <class 'bool'>

使用 globals() 批量导入配置

config.py

import configparser

config_path = "./config.ini"
config = configparser.ConfigParser()
config.read(config_path)

for section in config.sections():
    for key in config.options(section):
        globals()[key] = config[section][key]

main.py

import config as config

print(config.config_path)  # ./config.ini
print(config.browser)  # Chrome
print(config.user)  # root

写入配置

import configparser

config_path = "./config.ini"
config = configparser.ConfigParser()
# config.read(config_path)

# ===== 写入新配置 =====
config.add_section('login')  # 添加一个新的 section
config.set('login', 'username', 'admin')  # 写入数据
config.set('login', 'password', '123456')  # 写入数据
# ===== 如果已经使用 read 读取配置,可直接使用 open(config_path, 'w') 覆盖写入 =====
config.write(open(config_path, 'a'))  # 保存数据

config.ini

[select]
browser=Chrome
url=https://baidu.com

[mysql]
host=localhost
user=root
password=123456
port=3306
db=test

[config]
int_value=1
float_value=2.3
bool_value=False

[login]
username = admin
password = 123456
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值