求助:如何自动美化YAML文件并移除花括号格式?
I've run into this exact frustration before—generic YAML formatters often either leave small inline {} dictionaries untouched or strip out comments entirely, which is a pain when you need to keep your original annotations intact. Here’s a reliable solution using ruamel.yaml (a YAML library built specifically to preserve comments and formatting details that PyYAML ignores):
Step 1: Install the required library
First, grab ruamel.yaml via pip—it’s the best tool for this job because it maintains your comment structure:
pip install ruamel.yaml
Step 2: Run this custom formatting script
Create a tiny Python script to process your file. It’ll expand inline dictionaries to block-style indentation while keeping your comments and original quote formatting:
from ruamel.yaml import YAML # Initialize YAML handler with settings to retain your file's details yaml = YAML() yaml.preserve_quotes = True # Keeps your original single quotes around strings yaml.default_flow_style = False # Forces all dictionaries to use indented block style instead of {} # Load the original YAML file with open('SashaPrettifyYAML.yaml', 'r') as input_file: yaml_data = yaml.load(input_file) # Write the formatted output to a new file (or overwrite the original if you're confident) with open('formatted_SashaPrettifyYAML.yaml', 'w') as output_file: yaml.dump(yaml_data, output_file)
Result you’ll get
After running the script, your output file will match exactly what you wanted:
sasha_commands: # Sasha comment sasha_command_help: call: sublime.command_help caption: 'Sasha Command: Command Help'
Why your previous tools didn’t work
- PyYAML-based tools: PyYAML doesn’t preserve comments by default, so it would strip out your
# Sasha commentline entirely. Even if you forced formatting, it often skips expanding small inline dictionaries. - Online formatters: Most use basic PyYAML setups or don’t prioritize expanding short inline structures, plus they risk losing comments in the process.
内容的提问来源于stack exchange,提问作者Саша Черных

