Home > Blockchain >  Writing to Console and File in Python Script
Writing to Console and File in Python Script

Time:11-20

I am looking for some help on a project I am doing where I need to output the responses to the console as well as write them to a file. I am having trouble figuring that part out. I have been able to write the responses to a file successfully, but not both at the same time. Can someone help with that portion? The only lines that need to be written to the file are the ones that I have currently being written to a file

from datetime import datetime
import requests
import pytemperature


def main():
    api_start = 'https://api.openweathermap.org/data/2.5/weather?q='
    api_key = '&appid=91b8698c2ed6c192aabde7c9e75d23cb'
    now = datetime.now()

    filename = input("\nEnter the output filename: ")
    myfile = None
    try:
        myfile = open(filename, "w")
    except:
        print("Unable to open file "   filename  
              "\nData will not be saved to a file")

    choice = "y"

    print("ISQA 3900 Open Weather API", file=myfile)
    print(now.strftime("%A, %B %d, %Y"), file=myfile)

    while choice.lower() == "y":
        # input city and country code
        city = input("Enter city: ")
        print("Use ISO letter country code like: https://countrycode.org/")
        country = input("Enter country code: ")

        # app configures url to generate json data
        url = api_start   city   ','   country   api_key
        json_data = requests.get(url).json()

        try:
            # getting weather data from json
            weather_description = json_data['weather'][0]['description']

            # printing weather information
            print("\nThe Weather Report for "   city   " in "   country   " is:", file=myfile)
            print("\tCurrent conditions: ", weather_description, file=myfile)

            # getting temperature data from json
            current_temp_kelvin = json_data['main']['temp']
            current_temp_fahrenheit = pytemperature.k2f(current_temp_kelvin)

            # printing temperature information
            print("\tCurrent temperature in Fahrenheit:", current_temp_fahrenheit, file=myfile)

            # getting pressure data from json
            current_pressure = json_data['main']['pressure']

            # printing pressure information
            print("\tCurrent pressure in HPA:", current_pressure, file=myfile)

            # getting humidity data from json
            current_humidity = json_data['main']['humidity']

            # printing humidity information
            print("\tCurrent humidity:", "%s%%" % current_humidity, file=myfile)

            # getting expected low temp data from json
            expected_low_temp = json_data['main']['temp_min']
            expected_low_temp = pytemperature.k2f(expected_low_temp)

            # printing expected low temp information
            print("\tExpected low temperature in Fahrenheit:", expected_low_temp, file=myfile)

            # getting expected high temp data from json
            expected_high_temp = json_data['main']['temp_max']
            expected_high_temp = pytemperature.k2f(expected_high_temp)

            # printing expected high temp information
            print("\tExpected high temperature in Fahrenheit:", expected_high_temp, file=myfile)

            choice = input("Continue (y/n)?: ")
            print()

        except:
            print("Unable to access ", city, " in ", country)
            print("Verify city name and country code")

    if myfile:
        myfile.close()
    print('Thank you - Goodbye')


if __name__ == "__main__":
    main()

Honestly I am kind of at a loss on this one for some reason it is just kicking my butt.

CodePudding user response:

For printing a single object:

def mprint(text, file):
    print(text)
    print(text, file = file)

A more general one for printing several objects:

def mprint(*args):
   print(*args[:-1])
   print(*args[:-1],file = args[-1])

Usage: mprint(obj1, obj2, ... , myfile)

CodePudding user response:

A completely general print function replacement would look something like:

def myprint(*args, file=None, **kwargs):
    print(*args, **kwargs)            # print to screen
    if file is not None:
        print(*args, file=fp, **kwargs)   # print to file

this will let you use end=.. etc. as well

    filename = input("\nEnter the output filename: ")
    myfile = None
    try:
        myfile = open(filename, "w")
    except:
        print("Unable to open file "   filename  
              "\nData will not be saved to a file")

    choice = "y"

    myprint("ISQA 3900 Open Weather API", file=myfile)
    myprint(now.strftime("%A, %B %d, %Y"), file=myfile)

if myfile couldn't be opened and is therefore None, the myprint function will only print to screen.

  • Related