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

如何用ConfigParser将配置对象转为INI/TOML格式字符串?

用ConfigParser将配置对象转为字符串的方法

ConfigParser本身没有直接的write_string()方法,但可以借助io.StringIO内存缓冲区实现需求,无需手动循环拼接字符串:

import configparser
from io import StringIO

# Python 3.10+支持indentation参数控制键值对缩进
config = configparser.ConfigParser(indentation=4)

sample_config = """
[settings]
user = jeff
help = pls
"""
config.read_string(sample_config)

config["settings"]["user"] = "Orili"

# 用StringIO作为缓冲区捕获配置内容
buffer = StringIO()
config.write(buffer)
sample_config = buffer.getvalue()

print(sample_config)

执行后输出:

[settings]
    user = Orili
    help = pls

补充说明

  • config.write()方法默认接收文件类对象,StringIO模拟了文件操作接口,能把配置内容写入内存缓冲区,再通过getvalue()读取完整字符串
  • 若使用Python 3.10以下版本,可通过修改config._indent_width = 4来设置缩进,实现相同格式效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:02:02