1. import json
  2. import os
  3. import logging
  4. # Configure logging
  5. logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
  6. def serialize_text_files(directory):
  7. """
  8. Serializes objects from text files in a directory to JSON files.
  9. Logs errors encountered during processing.
  10. """
  11. for filename in os.listdir(directory):
  12. if filename.endswith(".txt"):
  13. filepath = os.path.join(directory, filename)
  14. try:
  15. with open(filepath, 'r') as f:
  16. lines = f.readlines()
  17. # Assuming each line represents a key-value pair. Adapt parsing as needed
  18. data = {}
  19. for line in lines:
  20. if line.strip(): # ignore empty lines
  21. try:
  22. key, value = line.split("=", 1) # split only at the first '='
  23. data[key.strip()] = value.strip()
  24. except ValueError:
  25. logging.error(f"Skipping invalid line in {filename}: {line.strip()}")
  26. continue
  27. output_filename = os.path.splitext(filename)[0] + ".json"
  28. output_filepath = os.path.join(directory, output_filename)
  29. with open(output_filepath, 'w') as outfile:
  30. json.dump(data, outfile, indent=4)
  31. print(f"Serialized {filename} to {output_filename}")
  32. except FileNotFoundError:
  33. logging.error(f"File not found: {filepath}")
  34. except Exception as e:
  35. logging.error(f"Error processing {filepath}: {e}")
  36. if __name__ == "__main__":
  37. # Replace with the directory containing your text files
  38. target_directory = "data"
  39. # Create the directory if it doesn't exist
  40. if not os.path.exists(target_directory):
  41. os.makedirs(target_directory)
  42. # Create some sample data for testing
  43. with open(os.path.join(target_directory, "file1.txt"), "w") as f:
  44. f.write("name=John Doe\n")
  45. f.write("age=30\n")
  46. f.write("city=New York\n")
  47. with open(os.path.join(target_directory, "file2.txt"), "w") as f:
  48. f.write("product=Laptop\n")
  49. f.write("price=1200\n")
  50. f.write("quantity=5\n")
  51. with open(os.path.join(target_directory, "invalid.txt"), "w") as f:
  52. f.write("bad_line\n") #test invalid line handling
  53. f.write("key=value")
  54. serialize_text_files(target_directory)

Add your comment