1. import json
  2. import os
  3. def aggregate_config(config_dir, fallback_values):
  4. """
  5. Aggregates configuration values from files in a directory, using fallback values if a value is missing.
  6. Args:
  7. config_dir (str): The directory containing the configuration files.
  8. fallback_values (dict): A dictionary containing default values to use if a configuration file doesn't contain a specific key.
  9. Returns:
  10. dict: A dictionary containing the aggregated configuration values.
  11. """
  12. aggregated_config = fallback_values.copy() # Start with fallback values
  13. for filename in os.listdir(config_dir):
  14. if filename.endswith(".json"):
  15. filepath = os.path.join(config_dir, filename)
  16. try:
  17. with open(filepath, "r") as f:
  18. config = json.load(f)
  19. for key, value in config.items():
  20. if key not in aggregated_config:
  21. aggregated_config[key] = value # Add new key/value pair
  22. except (json.JSONDecodeError, FileNotFoundError) as e:
  23. print(f"Error reading {filename}: {e}")
  24. # Optionally log the error to a file
  25. return aggregated_config

Add your comment