import json
import os
import logging
# Configure logging
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
def serialize_text_files(directory):
"""
Serializes objects from text files in a directory to JSON files.
Logs errors encountered during processing.
"""
for filename in os.listdir(directory):
if filename.endswith(".txt"):
filepath = os.path.join(directory, filename)
try:
with open(filepath, 'r') as f:
lines = f.readlines()
# Assuming each line represents a key-value pair. Adapt parsing as needed
data = {}
for line in lines:
if line.strip(): # ignore empty lines
try:
key, value = line.split("=", 1) # split only at the first '='
data[key.strip()] = value.strip()
except ValueError:
logging.error(f"Skipping invalid line in {filename}: {line.strip()}")
continue
output_filename = os.path.splitext(filename)[0] + ".json"
output_filepath = os.path.join(directory, output_filename)
with open(output_filepath, 'w') as outfile:
json.dump(data, outfile, indent=4)
print(f"Serialized {filename} to {output_filename}")
except FileNotFoundError:
logging.error(f"File not found: {filepath}")
except Exception as e:
logging.error(f"Error processing {filepath}: {e}")
if __name__ == "__main__":
# Replace with the directory containing your text files
target_directory = "data"
# Create the directory if it doesn't exist
if not os.path.exists(target_directory):
os.makedirs(target_directory)
# Create some sample data for testing
with open(os.path.join(target_directory, "file1.txt"), "w") as f:
f.write("name=John Doe\n")
f.write("age=30\n")
f.write("city=New York\n")
with open(os.path.join(target_directory, "file2.txt"), "w") as f:
f.write("product=Laptop\n")
f.write("price=1200\n")
f.write("quantity=5\n")
with open(os.path.join(target_directory, "invalid.txt"), "w") as f:
f.write("bad_line\n") #test invalid line handling
f.write("key=value")
serialize_text_files(target_directory)
Add your comment