AtEchoOff

Python I/O File Debugging

Sep 27th, 2025 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | Source Code | 0 0
  1. #-------------------------app.py--------------------
  2.  
  3. import csv
  4.  
  5. def process_weather_data(filename):
  6.     """
  7.    Processes weather data from a CSV file.
  8.    
  9.    Args:
  10.        filename (str): The name of the CSV file.
  11.    
  12.    Returns:
  13.        A dictionary containing processed data or None if an error occurs.
  14.    """
  15.    
  16.     # Initialize variables to store results
  17.     total_temp = 0
  18.     record_count = 0
  19.     highest_temp = -float('inf')
  20.     lowest_temp = float('inf')
  21.     highest_temp_date = ""
  22.     lowest_temp_date = ""
  23.    
  24.     try:
  25.         with open(filename, mode='r') as file:
  26.             reader = csv.DictReader(file)
  27.             for row in reader:
  28.                 # Student's task: Add code here to process each row
  29.                 pass
  30.                
  31.         # Student's task: Add code here to calculate the average temperature
  32.        
  33.         return {
  34.             'average_temp': 0, # Update this with the calculated average
  35.             'highest_temp': highest_temp,
  36.             'highest_temp_date': highest_temp_date,
  37.             'lowest_temp': lowest_temp,
  38.             'lowest_temp_date': lowest_temp_date
  39.         }
  40.  
  41.     except FileNotFoundError:
  42.         print(f"Error: The file '{filename}' was not found.")
  43.         return None
  44.     except Exception as e:
  45.         print(f"An unexpected error occurred: {e}")
  46.         return None
  47.  
  48. # Main part of the script
  49. if __name__ == "__main__":
  50.     result = process_weather_data('weather_data.csv')
  51.     if result:
  52.         print("Weather Data Analysis:")
  53.         print(f"Average Temperature: {result['average_temp']:.2f}°F")
  54.         print(f"Highest Temperature: {result['highest_temp']}°F (on {result['highest_temp_date']})")
  55.         print(f"Lowest Temperature: {result['lowest_temp']}°F (on {result['lowest_temp_date']})")
  56.  
  57. #--------------------------weather_data.csv--------------------
  58. date,temperature_f
  59. 2023-01-01,35
  60. 2023-01-02,42
  61. 2023-01-03,45
  62. 2023-01-04,38
  63. 2023-01-05,29
  64. 2023-01-06,31
  65. 2023-01-07,48
  66. 2023-01-08,55
  67. 2023-01-09,49
  68. 2023-01-10,40
Advertisement
Add Comment
Please, Sign In to add comment