1. import json
  2. import os
  3. import datetime
  4. def export_results(results, filename="results.json"):
  5. """Exports results to a JSON file."""
  6. try:
  7. with open(filename, 'w') as f:
  8. json.dump(results, f, indent=4) # Use indent for readability
  9. print(f"Results exported to {filename}")
  10. except Exception as e:
  11. print(f"Error exporting results: {e}")
  12. def get_user_input(prompt, input_type=str):
  13. """Gets user input with specified type, handling older Python versions."""
  14. while True:
  15. try:
  16. user_input = input(prompt)
  17. if input_type == int:
  18. return int(user_input)
  19. elif input_type == float:
  20. return float(user_input)
  21. else:
  22. return user_input
  23. except ValueError:
  24. print("Invalid input. Please try again.")
  25. def main():
  26. """Main function to gather input and export results."""
  27. # Get user input
  28. name = get_user_input("Enter your name: ")
  29. age = get_user_input("Enter your age: ", int)
  30. city = get_user_input("Enter your city: ")
  31. score = get_user_input("Enter your score: ", float)
  32. # Create results dictionary
  33. results = {
  34. "name": name,
  35. "age": age,
  36. "city": city,
  37. "score": score,
  38. "timestamp": datetime.datetime.now().isoformat() # Add timestamp
  39. }
  40. # Export results
  41. export_results(results)
  42. if __name__ == "__main__":
  43. main()

Add your comment