You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Python配置模块写入数据?修改配置字典无效问题咨询

如何修改Python模块式配置文件的内容

你直接执行config.truck['color'] = "yellow"只能修改内存中已导入的模块对象里的字典值,不会将修改同步到磁盘上的config.py文件,程序重启后配置会恢复成原来的内容。

下面是几种可行的解决方式:

方式一:手动将内存配置写回.py文件

通过将内存中的配置数据转换成符合Python语法的字符串,写入原配置文件。可以借助pprint来生成格式美观的代码:

import config
from pprint import pformat

def save_py_config():
    # 定义需要保存的配置变量
    config_items = [
        ('truck', config.truck),
        ('city', config.city),
        ('cabriolet', config.cabriolet)
    ]
    # 写入配置文件
    with open('config.py', 'w', encoding='utf-8') as f:
        for key, value in config_items:
            f.write(f"{key} = {pformat(value)}\n\n")

# 修改内存中的配置
config.truck['color'] = "yellow"
# 保存到磁盘文件
save_py_config()

方式二:改用JSON格式配置(更推荐)

JSON是Python原生支持的配置格式,读写逻辑简单,结构清晰,避免直接操作.py文件的麻烦:

  1. 将原配置改成config.json文件:
{
    "truck": {
        "color": "blue",
        "brand": "ford"
    },
    "city": "new york",
    "cabriolet": {
        "color": "black",
        "engine": {
            "cylinders": 8,
            "placement": "mid"
        },
        "doors": 2
    }
}
  1. 读写配置的代码:
import json

def load_config():
    with open('config.json', 'r', encoding='utf-8') as f:
        return json.load(f)

def save_config(config_data):
    with open('config.json', 'w', encoding='utf-8') as f:
        json.dump(config_data, f, indent=4, ensure_ascii=False)

# 使用示例
config = load_config()
print(config['truck']['color'])  # 输出 blue
config['truck']['color'] = "yellow"
save_config(config)  # 将修改写入文件

方式三:使用configparser处理INI格式配置

如果偏好INI格式的分段配置,可以使用Python标准库configparser,适合结构化的键值对配置:

  1. 配置文件config.ini:
[truck]
color = blue
brand = ford

[general]
city = new york

[cabriolet]
color = black
doors = 2

[cabriolet.engine]
cylinders = 8
placement = mid
  1. 读写代码:
from configparser import ConfigParser

def load_config():
    cfg = ConfigParser()
    cfg.read('config.ini', encoding='utf-8')
    return cfg

def save_config(cfg):
    with open('config.ini', 'w', encoding='utf-8') as f:
        cfg.write(f)

# 使用示例
config = load_config()
print(config['truck']['color'])  # 输出 blue
config['truck']['color'] = "yellow"
save_config(config)  # 保存修改

内容的提问来源于stack exchange,提问作者user1438082

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:07:01