|
1 | 1 | import requests |
2 | | -import os |
3 | 2 | from datetime import datetime |
4 | 3 |
|
5 | | -api_key = "Enter your api key here" |
6 | | -location = input("\nEnter the city name : ") |
7 | | - |
8 | | -complete_api_link = ( |
9 | | - "https://api.openweathermap.org/data/2.5/weather?q=" |
10 | | - + location |
11 | | - + "&appid=" |
12 | | - + api_key |
13 | | -) |
14 | | -api_link = requests.get(complete_api_link) |
15 | | -api_data = api_link.json() |
16 | | - |
17 | | -# create variables to store and display data |
18 | | - |
19 | | -try: |
20 | | - temp_city = (api_data["main"]["temp"]) - 273.15 |
21 | | - weather_desc = api_data["weather"][0]["description"] |
22 | | - hmdt = api_data["main"]["humidity"] |
23 | | - wind_spd = api_data["wind"]["speed"] |
24 | | - date_time = datetime.now().strftime("%d %b %Y | %I:%M:%S %p") |
25 | | - |
26 | | - f = open("wetherinfo.txt", "w+") |
27 | | - f.write("-------------------------------------------------------------\n") |
28 | | - f.write("Weather Stats for - {} || {}\n".format(location.upper(), date_time)) |
29 | | - f.write("-------------------------------------------------------------\n") |
30 | | - |
31 | | - f.write("\tCurrent temperature is : {:.2f} °C\n".format(temp_city)) |
32 | | - f.write("\tCurrent weather desc : " + weather_desc + "\n") |
33 | | - f.write("\tCurrent Humidity : {} %\n".format(hmdt)) |
34 | | - f.write("\tCurrent wind speed : {} km/h \n".format(wind_spd)) |
35 | | - f.close() |
36 | | - print("Current temperature is: {:.2f} °C".format(temp_city)) |
37 | | - print("Current weather desc : " + weather_desc) |
38 | | - print("Current Humidity :", hmdt, "%") |
39 | | - print("Current wind speed :", wind_spd, "kmph") |
40 | | - |
41 | | -except KeyError as KE: |
42 | | - print("Enter a valid city") |
| 4 | + |
| 5 | +# Function to fetch weather data from OpenWeatherMap API |
| 6 | +def fetch_weather(api_key, location): |
| 7 | + try: |
| 8 | + # Constructing the API link with the provided API key and location |
| 9 | + complete_api_link = f"https://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}" |
| 10 | + |
| 11 | + # Sending GET request to OpenWeatherMap API |
| 12 | + api_link = requests.get(complete_api_link) |
| 13 | + |
| 14 | + # Parsing the JSON response |
| 15 | + api_data = api_link.json() |
| 16 | + |
| 17 | + # Returning the fetched weather data |
| 18 | + return api_data |
| 19 | + |
| 20 | + # Handling exceptions related to request errors |
| 21 | + except requests.exceptions.RequestException as e: |
| 22 | + print("Error fetching weather data:", e) |
| 23 | + return None |
| 24 | + |
| 25 | + |
| 26 | +# Function to write weather information to a text file |
| 27 | +def write_to_file(location, weather_data): |
| 28 | + try: |
| 29 | + # Opening the file "weatherinfo.txt" in write mode |
| 30 | + with open("weatherinfo.txt", "w+") as f: |
| 31 | + # Getting the current date and time |
| 32 | + date_time = datetime.now().strftime("%d %b %Y | %I:%M:%S %p") |
| 33 | + |
| 34 | + # 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") |
| 38 | + |
| 39 | + # Writing temperature information to the file |
| 40 | + if "main" in weather_data and "temp" in weather_data["main"]: |
| 41 | + f.write("\tCurrent temperature is : {:.2f} °C\n".format(weather_data["main"]["temp"] - 273.15)) |
| 42 | + |
| 43 | + # Writing weather description information to the file |
| 44 | + if "weather" in weather_data and weather_data["weather"]: |
| 45 | + f.write("\tCurrent weather desc : " + weather_data["weather"][0]["description"] + "\n") |
| 46 | + |
| 47 | + # Writing humidity information to the file |
| 48 | + if "main" in weather_data and "humidity" in weather_data["main"]: |
| 49 | + f.write("\tCurrent Humidity : {} %\n".format(weather_data["main"]["humidity"])) |
| 50 | + |
| 51 | + # Writing wind speed information to the file |
| 52 | + if "wind" in weather_data and "speed" in weather_data["wind"]: |
| 53 | + f.write("\tCurrent wind speed : {} km/h \n".format(weather_data["wind"]["speed"])) |
| 54 | + |
| 55 | + # Printing confirmation message after writing to file |
| 56 | + print("Weather information written to weatherinfo.txt") |
| 57 | + |
| 58 | + # Handling IOError when writing to file |
| 59 | + except IOError as e: |
| 60 | + print("Error writing to file:", e) |
| 61 | + |
| 62 | + |
| 63 | +# Main function |
| 64 | +def main(): |
| 65 | + # Printing welcome messages and instructions |
| 66 | + print("Welcome to the Weather Information App!") |
| 67 | + print("You need an API key to access weather data from OpenWeatherMap.") |
| 68 | + print("You can obtain your API key by signing up at https://home.openweathermap.org/users/sign_up") |
| 69 | + |
| 70 | + # Prompting the user to input API key and city name |
| 71 | + api_key = input("Please enter your OpenWeatherMap API key: ") |
| 72 | + location = input("Enter the city name: ") |
| 73 | + |
| 74 | + # Fetching weather data using the provided API key and location |
| 75 | + weather_data = fetch_weather(api_key, location) |
| 76 | + |
| 77 | + # Checking if weather data was successfully fetched |
| 78 | + if weather_data: |
| 79 | + # Writing weather information to file |
| 80 | + write_to_file(location, weather_data) |
| 81 | + |
| 82 | + # Printing weather information to console |
| 83 | + print("Current temperature is: {:.2f} °C".format(weather_data["main"]["temp"] - 273.15)) |
| 84 | + print("Current weather desc : " + weather_data["weather"][0]["description"]) |
| 85 | + print("Current Humidity :", weather_data["main"]["humidity"], "%") |
| 86 | + print("Current wind speed :", weather_data["wind"]["speed"], "kmph") |
| 87 | + else: |
| 88 | + # Printing error message if weather data fetching fails |
| 89 | + print("Failed to fetch weather data. Please check your input and try again.") |
| 90 | + |
| 91 | + |
| 92 | +# Ensuring the main function is executed when the script is run |
| 93 | +if __name__ == "__main__": |
| 94 | + main() |
0 commit comments