0
user_api = os.environ['Api_key']
location = input("Vpišite ime mesta: ")

def Vremenska_napoved():
    """Za kraj, ki ga uporabnik vnese mu funkcija izpiše stanje vremena za tisti trenutek"""

complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+location+"&appid="+user_api
api_link = requests.get(complete_api_link)
api_data = api_link.json()

if api_data ['cod'] == '404':
    print("Mesto ne obstaja: {}, Preverite pravilni vnos mesta za katerega želite vremensko napoved".format(location))
else:
    #naredimo spremenljivke za shranjevanje in prikaz podatkov o vremenu
    Temperatura = ((api_data['main']['temp']) - 273.15)
    Vlažnost = api_data['main']['humidity']
    Hitrost_vetra = api_data['wind']['speed']
    Občuti_se_kot = api_data['weather'][0]['description']
    Datum_čas = datetime.now().strftime("%d %b %Y | %I:%M:%S %p")




    print ("_____________________________________________________________")
    print ("Vremenska napoved za - {} || {}".format(location.upper(), Datum_čas))
    print ("_____________________________________________________________")

    print ("Trenutna temperatura: {:.2f} stopinj C".format(Temperatura))
    print ("Trenutna vlažnost:",Vlažnost, '%')
    print ("Trenutna hitrost vetra:",Hitrost_vetra ,'km/h')
    print ("Občuti se kot:",Občuti_se_kot)

Vremenska_napoved()

Weather in PODBREZJE || 03 May 2021 | 07:13:32 PM


Temp: 12.54 stopinj C Hum: 54 % W_speed: 3.09 km/h

So this is my code and the output given by python and I am wondering how I could save Temp, Hum and W_speed into the CSV file, because I want to collect weather data for 1 day and process it.

4
  • 2
    Hi! You could use pandas to store the values in a dataframe and store the output in a csv file! Commented May 7, 2021 at 10:40
  • I have already tried (saving in excel) but I do not know exactly how to use Temp, Hum, W_speed in the code. import pandas as pd podatki = pd.DataFrame({'Temp':[],'Hum':[],'W_speed':[]}) podatki_v_excel = pd.ExcelWriter("FromPython.xlsx",engine = 'xlsxwriter') podatki.to_excel(podatki_v_excel,sheet_name = 'Zvezek1') podatki_v_excel.save() Commented May 7, 2021 at 10:54
  • Could you provide the json result of the api request? Commented May 7, 2021 at 10:55
  • Irrelevant to the question, but the Vremenska_napoved() function does absolutely nothing Commented May 7, 2021 at 15:31

1 Answer 1

2

Here you have the answer!

The data is stored in a dictionary and a csv is created appending the new data. If the file does not exists, the headers are added to the file.

I haven't tried the solution but the 'pseudocode' could help you with your requirements!

import os
import csv

user_api = os.environ['Api_key']
location = input("Vpišite ime mesta: ")

def Vremenska_napoved():
    """Za kraj, ki ga uporabnik vnese mu funkcija izpiše stanje vremena za tisti trenutek"""

    complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+location+"&appid="+user_api
    api_link = requests.get(complete_api_link)
    api_data = api_link.json()

    if api_data ['cod'] == '404':
        print("Mesto ne obstaja: {}, Preverite pravilni vnos mesta za katerega želite vremensko napoved".format(location))
    else:
        #naredimo spremenljivke za shranjevanje in prikaz podatkov o vremenu
        Temperatura = ((api_data['main']['temp']) - 273.15)
        Vlažnost = api_data['main']['humidity']
        Hitrost_vetra = api_data['wind']['speed']
        Občuti_se_kot = api_data['weather'][0]['description']
        Datum_čas = datetime.now().strftime("%d %b %Y | %I:%M:%S %p")


        headers = ['Date', 'Temp', 'Hum', 'W_speed']
        filename = 'output.csv'
        file_exists = os.path.isfile(filename)

        row = {
            'Date': Datum_čas
            'Temp': Temperatura,
            'Hum': Vlažnost,
            'W_speed': Hitrost_vetra
        }
        
        a_file = open(filename, "a")
        dict_writer = csv.DictWriter(a_file, headers)

        if not file_exists:
            dict_writer.writeheader()  # file doesn't exist yet, write a header

        dict_writer.writerow(row)
        a_file.close())

        print ("_____________________________________________________________")
        print ("Vremenska napoved za - {} || {}".format(location.upper(), Datum_čas))
        print ("_____________________________________________________________")

        print ("Trenutna temperatura: {:.2f} stopinj C".format(Temperatura))
        print ("Trenutna vlažnost:",Vlažnost, '%')
        print ("Trenutna hitrost vetra:",Hitrost_vetra ,'km/h')
        print ("Občuti se kot:",Občuti_se_kot)

Vremenska_napoved()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. I tried the code and it works as needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.