How to save the result to a file?

1

Well, I'm doing a program that takes the spaces of sentences, letters, words, and puts each "phrase / letter / word" one underneath the other.

For example: The "phrase / letter / word": BAB BBA ACA AAB BCB CBB ABC CBC BBB ACA BCB CBA CBA CCB ACB BAA BBC ACB BCB

He takes out the spaces, and puts one underneath the other. I'll leave a print, showing, to make it easier.

Mysourcecode

string_qualquer=input("Digite o texto: ")

for x in string_qualquer.split():
    print(x)

How do I save the result, instead of just printing on the screen?

Running Program:

    
asked by anonymous 12.01.2018 / 00:52

1 answer

3

The print function has an argument called file , which defines the destination of the message. By default, the value of the argument is sys.stdout , which is responsible for displaying the messages on the screen. If you want to write to file, just pass the pointer to the file as a parameter:

string_qualquer = input("Digite o texto: ")

with open("resultado.txt", "w") as stream:
    for x in string_qualquer.split():
        print(x, file=stream)

See working at Repl.it

So the result will be stored in the file resultado.txt

    
12.01.2018 / 00:59