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

如何使用Python删除Jenkins配置YAML文件中的unclassified与location块

Python处理YAML删除指定块实现方案

前置依赖

首先安装PyYAML库用于YAML文件的解析和生成:

pip install pyyaml

完整实现代码

import yaml

# 按需修改为你的实际文件路径
input_file = "jenkins_config.yaml"
output_file = "jenkins_config_updated.yaml"

# 读取解析原YAML文件
with open(input_file, 'r', encoding='utf-8') as f:
    config = yaml.safe_load(f)

# 删除根节点的unclassified块,其下的location块会同步被删除
if 'unclassified' in config:
    del config['unclassified']

# 若存在其他层级的location块需要删除,可自行补充对应层级的删除逻辑,例如删除根节点下的location:
# if 'location' in config:
#     del config['location']

# 写入处理后的配置,保留原有顺序和字符格式
with open(output_file, 'w', encoding='utf-8') as f:
    yaml.dump(
        config,
        f,
        allow_unicode=True,
        sort_keys=False,
        default_flow_style=False,
        indent=2
    )

print(f"处理完成,新配置已保存至{output_file}")

注意事项

  • 代码会保留原YAML的键顺序,不会自动排序打乱原有配置结构
  • 所有加密密码、格式字符串等内容都会原样保留,不会被修改
  • 建议操作前备份原配置文件,避免误操作导致数据丢失
  • 如果需要直接覆盖原文件,把output_file路径修改为和input_file一致即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:45:03