依次读取三个TOML文件并合并,后续文件覆盖之前的值,最终将结果写入新文件
import toml
def deep_update(base_dict, update_dict):
"""
递归合并字典,后续字典的值覆盖前者[6]
"""
for key, val in update_dict.items():
if isinstance(val, dict):
if key in base_dict and isinstance(base_dict[key], dict):
deep_update(base_dict[key], val)
else:
base_dict[key] = val.copy()
else:
base_dict[key] = val
return base_dict
def merge_toml_files(file_paths, output_path):
merged = {}
for path in file_paths:
with open(path, "r", encoding="utf-8") as f:
current = toml.load(f) # 读取TOML文件[2,7]
deep_update(merged, current)
with open(output_path, "w", encoding="utf-8") as f:
toml.dump(merged, f) # 写入合并后的配置[3,6]
if __name__ == "__main__":
input_files = ["file1.toml", "file2.toml", "file3.toml"]
output_file = "merged.toml"
merge_toml_files(input_files, output_file)