1. import json
  2. import os
  3. import datetime
  4. def sync_user_data(source_path, dest_path):
  5. """Syncs user data from source to destination, handling errors."""
  6. try:
  7. # Read data from source
  8. with open(source_path, 'r') as f:
  9. try:
  10. data = json.load(f)
  11. except json.JSONDecodeError:
  12. print(f"Error: Could not decode JSON from {source_path}. File may be corrupted.")
  13. return False
  14. # Create destination directory if it doesn't exist
  15. os.makedirs(dest_path, exist_ok=True)
  16. # Generate timestamped filename
  17. timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  18. dest_file = os.path.join(dest_path, f"user_data_{timestamp}.json")
  19. # Write data to destination
  20. with open(dest_file, 'w') as f:
  21. json.dump(data, f, indent=4)
  22. print(f"Successfully synced data to {dest_file}")
  23. return True
  24. except FileNotFoundError:
  25. print(f"Error: Source file not found at {source_path}")
  26. return False
  27. except Exception as e:
  28. print(f"An unexpected error occurred: {e}")
  29. return False
  30. if __name__ == '__main__':
  31. # Example usage
  32. source_file = "user_data_source.json"
  33. destination_dir = "user_data_destination"
  34. # Create a dummy source file for testing
  35. dummy_data = {"user_id": 123, "name": "John Doe", "email": "john.doe@example.com"}
  36. with open(source_file, 'w') as f:
  37. json.dump(dummy_data, f, indent=4)
  38. sync_user_data(source_file, destination_dir)

Add your comment