How to save the result to a file?

Asked

Viewed 1,870 times

1

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

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

It removes the spaces, and puts one underneath the other. I’ll leave a print, showing, to make it easier.

inserir a descrição da imagem aqui

My source code

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?

Programme under implementation:

inserir a descrição da imagem aqui

1 answer

3


The function print has an argument called file, that defines the destination of the message. By default, the argument value is sys.stdout, which is responsible for displaying the messages on the screen. If you want to write to a file, simply pass the pointer to the file as 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 on Repl.it

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

  • It worked fine buddy, thanks! The excerpt "with open("result.txt", "w") as stream:" is a file-opening mode, right? Another question, do you have in python’s Ocs explaining this type of file opening? Because I use that conventional one. Ex: "File = open("qualquername.txt", "w")".

  • @Brkappa in a way, yes. Read more on: https://answall.com/q/49238/5878

  • Thank you for having solved my doubts!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.