Python 脚本:递归加载和重新保存 YAML
这可用于修复 PyYAML 生成的 YAML 文件格式与任何手动生成的文件略有不同的问题。例如,你可以先使用此脚本生成仅重新保存的干净差异,然后运行另一个脚本来修改 YAML 以获得更干净的差异。
resave_yamls.py
#!/usr/bin/env python3
import argparse
import yaml
import pathlib
def load_and_save_yaml(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
data = yaml.safe_load(file)
with open(file_path, 'w', encoding='utf-8') as file:
yaml.safe_dump(data, file)
def process_files(file_paths):
for file_path in file_paths:
try:
load_and_save_yaml(file_path)
print(f"Processed: {file_path}")
except Exception as e:
print(f"Failed to process {file_path}: {e}")
def main():
parser = argparse.ArgumentParser(description="Load and re-save YAML files.")
parser.add_argument('files', nargs='*', help="YAML files to process. If not provided, searches for all *.yaml files in the current directory and subdirectories.")
args = parser.parse_args()
if args.files:
file_paths = [pathlib.Path(file) for file in args.files]
else:
file_paths = list(pathlib.Path('.').rglob('*.yaml'))
process_files(file_paths)
if __name__ == "__main__":
main()Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow