|
| 1 | +import glob |
1 | 2 | import os
|
2 | 3 |
|
3 | 4 | import yaml
|
|
6 | 7 | def merge_yaml_files(directory, output_file):
|
7 | 8 | merged_data = [] # Initialize an empty list to hold merged data
|
8 | 9 |
|
9 |
| - # Iterate over all files in the directory |
10 |
| - for filename in sorted(os.listdir(directory)): |
11 |
| - if filename.endswith(".yml") or filename.endswith(".yaml"): |
12 |
| - file_path = os.path.join(directory, filename) |
13 |
| - with open(file_path, "r") as file: |
14 |
| - # Load the YAML data while preserving order |
15 |
| - data = yaml.load(file, Loader=yaml.SafeLoader) # Use SafeLoader |
16 |
| - |
17 |
| - # Check if the loaded data is a dictionary |
18 |
| - if isinstance(data, dict): |
19 |
| - merged_data.append(data) # Append the dictionary to merged_data |
20 |
| - else: |
21 |
| - print( |
22 |
| - f"Warning: The content of {filename} is not a dictionary. Skipping." |
23 |
| - ) |
| 10 | + # Find all YAML files recursively in subdirectories |
| 11 | + |
| 12 | + yaml_files = glob.glob(os.path.join(directory, "**", "*.yml"), recursive=True) |
| 13 | + yaml_files.extend( |
| 14 | + glob.glob(os.path.join(directory, "**", "*.yaml"), recursive=True) |
| 15 | + ) |
| 16 | + |
| 17 | + # Process each YAML file found |
| 18 | + for file_path in sorted(yaml_files): |
| 19 | + filename = os.path.basename(file_path) |
| 20 | + with open(file_path, "r") as file: |
| 21 | + # Load the YAML data while preserving order |
| 22 | + data = yaml.load(file, Loader=yaml.SafeLoader) # Use SafeLoader |
| 23 | + |
| 24 | + # Check if the loaded data is a dictionary |
| 25 | + if isinstance(data, dict): |
| 26 | + merged_data.append(data) # Append the dictionary to merged_data |
| 27 | + else: |
| 28 | + print( |
| 29 | + f"Warning: The content of {filename} is not a dictionary. Skipping." |
| 30 | + ) |
24 | 31 |
|
25 | 32 | # Write the merged data to the output YAML file
|
26 | 33 | with open(output_file, "w") as outfile:
|
|
0 commit comments