1. import json
  2. import os
  3. def nest_text_files(root_dir, default_values=None):
  4. """
  5. Nests structures of text files into a single JSON file.
  6. Args:
  7. root_dir (str): Path to the directory containing text files.
  8. default_values (dict, optional): Dictionary of default values to use if a key is missing in a text file. Defaults to None.
  9. Returns:
  10. str: Path to the generated JSON file.
  11. """
  12. data = {}
  13. for filename in os.listdir(root_dir):
  14. if filename.endswith(".txt"):
  15. filepath = os.path.join(root_dir, filename)
  16. try:
  17. with open(filepath, "r") as f:
  18. content = f.readlines()
  19. # Assuming each line represents a key-value pair
  20. for line in content:
  21. line = line.strip()
  22. if line: # Skip empty lines
  23. try:
  24. key, value = line.split("=", 1)
  25. key = key.strip()
  26. value = value.strip()
  27. if key not in data:
  28. data[key] = value
  29. except ValueError:
  30. print(f"Skipping invalid line in {filename}: {line}")
  31. except FileNotFoundError:
  32. print(f"File not found: {filepath}")
  33. except Exception as e:
  34. print(f"Error processing {filepath}: {e}")
  35. if default_values:
  36. for key, default_value in default_values.items():
  37. if key not in data:
  38. data[key] = default_value
  39. output_file = os.path.join(root_dir, "combined.json")
  40. with open(output_file, "w") as f:
  41. json.dump(data, f, indent=4)
  42. return output_file

Add your comment