Skip to content
This repository was archived by the owner on Apr 24, 2025. It is now read-only.

Commit 3c720cc

Browse files
Merge pull request #715 from LightxAman/LightxAman
Hello, this is my attempt to enhance the previous code for project "API based weather report"
2 parents 43eb4fe + 7775859 commit 3c720cc

2 files changed

Lines changed: 139 additions & 39 deletions

File tree

Lines changed: 91 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,94 @@
11
import requests
2-
import os
32
from datetime import datetime
43

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()
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Weather Information App
2+
3+
Welcome to the Weather Information App! This application allows users to fetch current weather information for a specific city using the OpenWeatherMap API. The fetched data is then displayed on the console and saved to a text file for future reference.
4+
5+
## Features
6+
7+
- Fetches current weather data from OpenWeatherMap API.
8+
- Displays weather information including temperature, weather description, humidity, and wind speed.
9+
- Writes weather information to a text file for offline access.
10+
11+
## Prerequisites
12+
13+
- Python 3.x installed on your system.
14+
- OpenWeatherMap API key. You can obtain it by signing up at [OpenWeatherMap](https://home.openweathermap.org/users/sign_up).
15+
16+
## Usage
17+
18+
1. Obtain your OpenWeatherMap API key by signing up at [OpenWeatherMap](https://home.openweathermap.org/users/sign_up).
19+
20+
2. Run the application:
21+
22+
```bash
23+
python weather_app.py
24+
```
25+
26+
## Usage
27+
28+
1. Obtain your OpenWeatherMap API key by signing up at [OpenWeatherMap](https://home.openweathermap.org/users/sign_up).
29+
30+
2. Run the application:
31+
32+
```bash
33+
python weather_app.py
34+
```
35+
36+
3. Follow the on-screen prompts to enter your API key and the city name for which you want to fetch weather information.
37+
38+
**Note:** When entering the city name, ensure to provide the following:
39+
- Exact City Name: Spell the city name correctly to ensure accurate results (e.g., "New York", "London").
40+
- City Name and Country Code (Optional): Use the format "City, Country Code" to specify the country if needed (e.g., "London, UK", "Springfield, US").
41+
- Special Characters: Input special characters or diacritics correctly if applicable (e.g., "Paris", "München").
42+
- Alternative Names: Use alternative or local names if known (e.g., "Mumbai" for "Bombay").
43+
- City Name with Spaces: Input the city name with spaces as it appears (e.g., "Los Angeles", "San Francisco").
44+
- City District or Area (Optional): Specify a district or area within larger cities for more localized weather data (e.g., "Manhattan, New York", "Shinjuku, Tokyo").
45+
46+
## License
47+
48+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

0 commit comments

Comments
 (0)