11import requests
22from datetime import datetime
3+ from Util_Functions import wind_degree_to_direction , unix_timestamp_to_localtime , convert_temperature
34
45
5- # Function to fetch weather data from OpenWeatherMap API
66def fetch_weather (api_key , location ):
7+ """
8+ Function to fetch weather data from OpenWeatherMap API.
9+
10+ Parameters:
11+ api_key (str): API key.
12+ location (str): City name.
13+
14+ Returns:
15+ str: The JSON response string.
16+ """
717 try :
818 # Constructing the API link with the provided API key and location
919 complete_api_link = f"https://api.openweathermap.org/data/2.5/weather?q={ location } &appid={ api_key } "
@@ -23,25 +33,34 @@ def fetch_weather(api_key, location):
2333 return None
2434
2535
26- # Function to write weather information to a text file
27- def write_to_file (location , weather_data ):
36+ def write_to_file (weather_data , temperature_unit ):
37+ """
38+ Function to write weather information to a text file.
39+
40+ Parameters:
41+ weather_data (str): The JSON API response string.
42+ temperature_unit (str): 'C' for Celsius, 'F' for Fahrenheit.
43+ """
44+
2845 try :
2946 # Opening the file "weatherinfo.txt" in write mode
3047 with open ("weatherinfo.txt" , "w+" ) as f :
3148 # Getting the current date and time
3249 date_time = datetime .now ().strftime ("%d %b %Y | %I:%M:%S %p" )
3350
3451 # Writing header information to the file
35- f .write ("-------------------------------------------------------------\n " )
36- f .write (f"Weather Stats for - { location .upper ()} || { date_time } \n " )
37- f .write ("-------------------------------------------------------------\n " )
52+ if "name" in weather_data and "sys" in weather_data and "country" in weather_data ["sys" ]:
53+ f .write ("-------------------------------------------------------------\n " )
54+ f .write (f"Weather Stats for - { weather_data ['name' ]} | { weather_data ['sys' ]['country' ]} "
55+ f"| { date_time } \n " )
56+ f .write ("-------------------------------------------------------------\n " )
3857
3958 # Writing temperature information to the file
4059 if "main" in weather_data and "temp" in weather_data ["main" ]:
4160 f .write (
42- "\t Current temperature is : {:.2f} °C \n " . format (
43- weather_data ["main" ]["temp" ] - 273.15
44- )
61+ "\t Current temperature is : "
62+ + convert_temperature ( weather_data ["main" ]["temp" ], temperature_unit )
63+ + " \n "
4564 )
4665
4766 # Writing weather description information to the file
@@ -68,6 +87,24 @@ def write_to_file(location, weather_data):
6887 )
6988 )
7089
90+ # Writing wind direction information to the file
91+ if "wind" in weather_data and "deg" in weather_data ["wind" ]:
92+ f .write (
93+ "\t Current wind direction : " +
94+ wind_degree_to_direction (weather_data ["wind" ]["deg" ]) + " \n " )
95+
96+ # Writing sunrise local time to the file
97+ if "sys" in weather_data and "sunrise" in weather_data ["sys" ] and "timezone" in weather_data :
98+ f .write (
99+ "\t Today's sunrise time : " +
100+ unix_timestamp_to_localtime (weather_data ["sys" ]["sunrise" ], weather_data ["timezone" ]) + " \n " )
101+
102+ # Writing sunset local time to the file
103+ if "sys" in weather_data and "sunset" in weather_data ["sys" ] and "timezone" in weather_data :
104+ f .write (
105+ "\t Today's sunset time : " +
106+ unix_timestamp_to_localtime (weather_data ["sys" ]["sunset" ], weather_data ["timezone" ]) + " \n " )
107+
71108 # Printing confirmation message after writing to file
72109 print ("Weather information written to weatherinfo.txt" )
73110
@@ -76,36 +113,59 @@ def write_to_file(location, weather_data):
76113 print ("Error writing to file:" , e )
77114
78115
79- # Main function
80116def main ():
117+ """
118+ Main function.
119+ """
81120 # Printing welcome messages and instructions
82121 print ("Welcome to the Weather Information App!" )
83122 print ("You need an API key to access weather data from OpenWeatherMap." )
84123 print (
85124 "You can obtain your API key by signing up at https://home.openweathermap.org/users/sign_up"
86125 )
87126
88- # Prompting the user to input API key and city name
127+ # Prompting the user to input API key, city name, and temperature unit
89128 api_key = input ("Please enter your OpenWeatherMap API key: " )
90129 location = input ("Enter the city name: " )
130+ temperature_unit = input ("Enter the temperature unit. 'C' for Celsius and 'F' for Fahrenheit: " )
131+
132+ if not (temperature_unit .upper () == "C" or temperature_unit .upper () == "F" ):
133+ print ("Temperature unit must either be 'C' or be 'F'." )
134+ return
91135
92136 # Fetching weather data using the provided API key and location
93137 weather_data = fetch_weather (api_key , location )
94138
95139 # Checking if weather data was successfully fetched
96140 if weather_data :
141+ # Checking if the API key is invalid
142+ if weather_data ["cod" ] == "401" :
143+ print ("Invalid API key." )
144+ return
145+
146+ # Checking if the city is not found
147+ if weather_data ["cod" ] == "404" :
148+ print ("City not found." )
149+ return
150+
97151 # Writing weather information to file
98- write_to_file (location , weather_data )
152+ write_to_file (weather_data , temperature_unit )
99153
100154 # Printing weather information to console
155+ print ("Current City : " + weather_data ['name' ] + ', ' +
156+ weather_data ['sys' ]['country' ])
101157 print (
102- "Current temperature is: {:.2f} °C" .format (
103- weather_data ["main" ]["temp" ] - 273.15
104- )
158+ "Current temperature is: "
159+ + convert_temperature (weather_data ["main" ]["temp" ], temperature_unit )
105160 )
106161 print ("Current weather desc : " + weather_data ["weather" ][0 ]["description" ])
107162 print ("Current Humidity :" , weather_data ["main" ]["humidity" ], "%" )
108163 print ("Current wind speed :" , weather_data ["wind" ]["speed" ], "kmph" )
164+ print ("Current wind direction:" , wind_degree_to_direction (weather_data ["wind" ]["deg" ]))
165+ print ("Today's sunrise time :" ,
166+ unix_timestamp_to_localtime (weather_data ["sys" ]["sunrise" ], weather_data ["timezone" ]))
167+ print ("Today's sunset time :" ,
168+ unix_timestamp_to_localtime (weather_data ["sys" ]["sunset" ], weather_data ["timezone" ]))
109169 else :
110170 # Printing error message if weather data fetching fails
111171 print ("Failed to fetch weather data. Please check your input and try again." )
0 commit comments