import json
import os
import datetime
def sync_user_data(source_path, dest_path):
"""Syncs user data from source to destination, handling errors."""
try:
# Read data from source
with open(source_path, 'r') as f:
try:
data = json.load(f)
except json.JSONDecodeError:
print(f"Error: Could not decode JSON from {source_path}. File may be corrupted.")
return False
# Create destination directory if it doesn't exist
os.makedirs(dest_path, exist_ok=True)
# Generate timestamped filename
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
dest_file = os.path.join(dest_path, f"user_data_{timestamp}.json")
# Write data to destination
with open(dest_file, 'w') as f:
json.dump(data, f, indent=4)
print(f"Successfully synced data to {dest_file}")
return True
except FileNotFoundError:
print(f"Error: Source file not found at {source_path}")
return False
except Exception as e:
print(f"An unexpected error occurred: {e}")
return False
if __name__ == '__main__':
# Example usage
source_file = "user_data_source.json"
destination_dir = "user_data_destination"
# Create a dummy source file for testing
dummy_data = {"user_id": 123, "name": "John Doe", "email": "john.doe@example.com"}
with open(source_file, 'w') as f:
json.dump(dummy_data, f, indent=4)
sync_user_data(source_file, destination_dir)
Add your comment