python
def copy_yaml_content(source_file, target_file):
# 确保源文件存在
if not os.path.exists(source_file):
raise FileNotFoundError(f"Source file {source_file} not found.")
# 读取源文件内容
with open(source_file, 'r', encoding='utf-8', errors='ignore') as file:
data = yaml.safe_load(file)
# 将数据写入目标文件
with open(target_file, 'w', encoding='utf-8', errors='ignore') as file:
yaml.dump(data, file, default_flow_style=False) # default_flow_style=False 保持可读性
source.yaml
是你要复制内容的源文件
target.yaml
是你要写入的目标文件
yaml.safe_load()
函数用于读取YAML文件的内容,并将其解析为Python数据结构(如字典、列表等)。然后,使用yaml.dump()
函数将这些数据写回到另一个YAML文件中。