import json
import os
def nest_text_files(root_dir, default_values=None):
"""
Nests structures of text files into a single JSON file.
Args:
root_dir (str): Path to the directory containing text files.
default_values (dict, optional): Dictionary of default values to use if a key is missing in a text file. Defaults to None.
Returns:
str: Path to the generated JSON file.
"""
data = {}
for filename in os.listdir(root_dir):
if filename.endswith(".txt"):
filepath = os.path.join(root_dir, filename)
try:
with open(filepath, "r") as f:
content = f.readlines()
# Assuming each line represents a key-value pair
for line in content:
line = line.strip()
if line: # Skip empty lines
try:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
if key not in data:
data[key] = value
except ValueError:
print(f"Skipping invalid line in {filename}: {line}")
except FileNotFoundError:
print(f"File not found: {filepath}")
except Exception as e:
print(f"Error processing {filepath}: {e}")
if default_values:
for key, default_value in default_values.items():
if key not in data:
data[key] = default_value
output_file = os.path.join(root_dir, "combined.json")
with open(output_file, "w") as f:
json.dump(data, f, indent=4)
return output_file
Add your comment