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

如何使用PyYAML修改YAML文件中含特殊字符的tokens字段?

Hey there! Let's figure out how to fix this since you can't use ruamel.yaml and PyYAML was throwing errors with those special template characters. We've got two solid approaches here:

1. Straightforward Text Replacement (Best for Fixed Format)

Since your goal is super specific—just modifying lines that start with - {tokens:—you don't even need to parse the YAML fully. Text replacement avoids all the parsing headaches with special characters and keeps your original YAML format intact.

Here's the code:

with open('test.yaml', 'r') as file:
    lines = file.readlines()

updated_lines = []
for line in lines:
    # Check if the line matches our target pattern (accounting for indentation)
    stripped_line = line.strip()
    if stripped_line.startswith('- {tokens:'):
        # Preserve the original indentation
        indentation = line[:line.find('- {tokens:')]
        # Build the modified line with empty tokens
        updated_line = f"{indentation}- {{tokens: ''}}\n"
        updated_lines.append(updated_line)
    else:
        updated_lines.append(line)

# Write the modified content back to the file
with open('test.yaml', 'w') as file:
    file.writelines(updated_lines)

This works because we're targeting exactly the lines we need to change, no YAML parsing required. Perfect for avoiding those template-related errors.

2. Fix PyYAML Parsing & Modify the Structure

If you really want to use PyYAML to parse and edit the YAML structure, you need to make sure it handles those special template characters correctly. The error probably came from not using the right loader or PyYAML misinterpreting the template syntax.

Try this code:

import yaml

# Load the YAML with FullLoader (safe and recommended for PyYAML 5.1+)
with open('test.yaml', 'r') as file:
    data = yaml.load(file, Loader=yaml.FullLoader)

# Update the tokens value to an empty string
data["list_provider"][0]["parameters"][0]["tokens"] = ''

# Write back with settings to match your original YAML format
with open("test.yaml", "w") as f:
    yaml.dump(
        data,
        f,
        default_flow_style=False,  # Use block-style format like your original
        sort_keys=False,           # Keep original key order (no sorting)
        indent=4                   # Match your original 4-space indentation
    )

A few notes on the dump settings:

  • default_flow_style=False prevents PyYAML from switching to compact flow notation
  • sort_keys=False stops it from reordering your YAML keys
  • indent=4 ensures the spacing matches your original file

Just keep in mind that PyYAML might still tweak some formatting (like quote styles) even with these settings. If preserving every detail of the original YAML is critical, stick with the text replacement method.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:44:45