Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving user output to file with while loop

Tags:

python

file

loops

I'm going through some exercises and I can't just figure this out.

Write a while loop that prompts users for their name. When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt. Make sure each entry appears on a new line in the file.

Honestly, I spent way to much time on that and it seems like I'm not understanding the logic of working with files. I think the f.write should be directly under with open in order for the user input to be saved in the file but that's as much as I know. Can you please help me?

My attempts:

filename = 'guest_book.txt'

with open(filename, 'w') as f:
    lines = input('Input your name to save in the file: ')
    while True:
        for line in lines:
            f.write(input('Input your name to save in the file'))

I had some more hopes for the second one but still doesn't work.

filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True

with open(filename, 'w') as f:
    while active:
        message = f.write(input(prompt))

        if message == 'quit':
            break
        else:
            print(message)
like image 260
Michal Patyjewicz Avatar asked Dec 04 '25 04:12

Michal Patyjewicz


1 Answers

A bit of rejigging will get the code as you've written it to work. The main issue is that you can't use the output of f.write() as the value of message, as it doesn't contain the message, it contains the number of characters written to the file, so it will never contain quit. Also, you want to do the write after you have checked for quit otherwise you will write quit to the file.

filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True

with open(filename, 'w') as f:
    while active:
        message = input(prompt)

        if message == 'quit':
            active = False
        else:
            f.write(message + '\n')
            print(message)

Note: I have changed the break to active = False as you have written it as while active:, but you would have been fine with just while True: and break

like image 158
David Buck Avatar answered Dec 06 '25 16:12

David Buck