V
V
vtaeke2020-08-31 13:23:31
Python
vtaeke, 2020-08-31 13:23:31

How to insert, read the contents of a file and output data from it?

There is a task: Guest book: write a while loop that in a loop asks users for names. As you enter each name, display a greeting and add a message line to a file called guest.txt. Make sure that each message is on a separate line in the file.

I can't save the entered value to a file, because I can't complete the loop even with the 'quit' command (not processed) and, in fact, output these values ​​from this ... In which direction should I look? I didn't quite catch the gap between the topics in the book.

filename = 'guest.txt'

name = "\nPlease enter your name:"
name += "\n(Enter 'quit' when you are finished.) "

while True:
    with open(filename, 'w') as file_object:
        file_object.write(input(name))
        file_object.write("Hello " + name)
        if name == 'quit':
            break
        else:
            print("Hello " + name + "!")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ramis, 2020-08-31
@vtaeke

If I understood the condition correctly, do I need to write their names in TXT, or the message that they write after the name?

filename = 'guest.txt'
text = "\nPlease enter your name:"
text += "\n(Enter 'quit' when you are finished.) "

while True:
    name = input(text)
    if name == 'quit':
        break
    else:
        print("Hello " + name + "!")
        with open(filename, 'a') as f:
            f.write(f'{name}\n')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question