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

使用configparser移除INI文件节名并保留其键值对

移除INI节头但保留键值对的解决方法

你当前用parser.remove_section('top')会直接删除整个节包括下属的键值对,这不符合需求。这里提供两种实用方法:

方法一:借助configparser处理(适配标准INI)

核心思路是先提取目标节的键值对,删除原节后将键值对存入DEFAULT节——因为configparser写入时,DEFAULT的内容会直接输出为无节头的键值对:

import configparser

parser = configparser.ConfigParser()
with open('testing.ini', "r") as configfile:
    parser.read_file(configfile)

# 提取目标节的所有键值对
section_kv = parser.items('top')
# 删除原节
parser.remove_section('top')
# 将键值对添加到DEFAULT节
for key, val in section_kv:
    parser.set('DEFAULT', key, val)

# 写入修改后的内容
with open('testing.ini', "w") as f:
    parser.write(f)

方法二:直接处理文本行(轻量灵活)

如果你的INI文件结构简单,直接逐行过滤节头行即可,无需依赖configparser:

# 读取原文件内容
with open('testing.ini', 'r') as f:
    lines = f.readlines()

# 过滤掉[top]节头行,同时清理空行(可选)
processed_lines = [line for line in lines if not line.strip().startswith('[top]') and line.strip()]

# 写入处理后的内容
with open('testing.ini', 'w') as f:
    f.writelines(processed_lines)

两种方法都能实现你的需求,将原文件的[top]节头移除,保留对应的键值对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:47:43