Brendan
Brendan

Reputation: 33

How do I write the output of one function to a file?

The function I want to the write the output of is:

def display_pokemon(pokemon_list):
    pokemon_count = 0
    for x in pokemon_list:
        pokemon_count += 1
        # Requirement 5
        print("Name of Pokemon #{}: ".format(pokemon_count), x.get_name())
        print("Ability of Pokemon #{}: ".format(pokemon_count), x.get_ability())

The list being passed through display_pokemon is populated by the user previously as display_pokemon then prints something like:

Name of Pokemon #1: Pikachu

Ability of Pokemon #1: Thunderbolt

And that output is what I want to collect from this function to write to a file.

Essentially this is how I want my main() to look:

def main():
    pokemon_list = add_pokemon()
    display_pokemon(pokemon_list)
    file_name = input("\nEnter the name of the file?: ")
    save_data(file_name)
    display_data(file_name)

Upvotes: 0

Views: 481

Answers (4)

Arvind Raghu
Arvind Raghu

Reputation: 458

The first change that you would make is to your display_pokemon. Instead of printing this string, you can add it to an array.

def display_pokemon(pokemon_list):
    output = []
    pokemon_count = 0
    for x in pokemon_list:
        pokemon_count += 1
        # Requirement 5
        print("Name of Pokemon #{}: ".format(pokemon_count), x.get_name())
        print("Ability of Pokemon #{}: ".format(pokemon_count), x.get_ability())
        # Writing to output
        output.append(f"Name of Pokemon #{pokemon_count}: {x.get_name()}")
        output.append(f"Ability of Pokemon #{pokemon_count}: {x.get_ability()}")
    return output

Then, just write to a file destination:

def main():
    pokemon_list = add_pokemon()
    to_write = display_pokemon(pokemon_list)

    file_name = r"some\file.txt"
    file = open(file_name, "w+")
    for i in to_write:
        file.write(i)
        file.write("\n")
  
    file.close()

EDIT: if you would like to have the writing in a save_file() function, then the code for main would be changed to:

def main() :
    pokemon_list = add_pokemon() 
    to_write = display_pokemon(pokemon_list)
    file_name = r"some/file.py"

    def save_file(file_name, to_write):
        file = open(file_name, "w+")
        for i in to_write:
            file.write(i)
            file.write("\n")
  
        file.close() 

    save_file(file_name, to_write) 

Upvotes: 2

Prem Anand
Prem Anand

Reputation: 2557

You can use the redirect_stdout context manager from contextlib to redirect the stdout temporarily For example, the following code would make the output of the function call display_pokemon() to a file named file_name

with open(file_name, 'w') as out, contextlib.redirect_stdout(out):
    display_pokemon(pokemon_list)

Upvotes: 0

chepner
chepner

Reputation: 532398

Your function currently uses sys.stdout as the hard-coded destination file for the calls to print. Make the file to use an argument instead; you can still use sys.stdout as the default.

def display_pokemon(pokemon_list, out=sys.stdout):
    for count, x in enumerate(pokemon_list, start=1):
        # Requirement 5
        print("Name of Pokemon #{}: ".format(count), x.get_name(), file=out)
        print("Ability of Pokemon #{}: ".format(count), x.get_ability(), file=out)

Now you can call the function as before to write to standard output, or pass a different file:

def main():
    pokemon_list = add_pokemon()
    with open(r'some\file.txt', 'w') as fh:
        display_pokemon(pokemon_list, out=fh)

Upvotes: 0

MercifulSory
MercifulSory

Reputation: 333

So what you want to do is:

def display_pokemon(pokemon_list):
    file_name = input('"\nEnter the name of the file?: "')
    with open(file_name, 'w') as file:
        pokemon_count = 0
        for x in pokemon_list:
            pokemon_count += 1
            # Requirement 5
            pokemon_name = "Name of Pokemon #{}: ".format(pokemon_count) + x.get_name()
            print(pokemon_name)
            file.write(pokemon_name + '\n')
            pokemon_ability = "Ability of Pokemon #{}: ".format(pokemon_count) + x.get_ability()
            print(pokemon_ability)
            file.write(pokemon_ability)

Upvotes: 0

Related Questions