D.Wes
D.Wes

Reputation: 27

Appending/Adding to a file in Python using a While Loop

With this program I am trying to add entries to an empty text file. Below is my code:

###Adding to an Empty File
filename = 'guest_book.txt'

message = input("Please enter your name for our records: ") # retrieving input

while message != 'finished': # checking for value that will end the program
    with open(filename, 'a') as f:
        f.write(message)

The program builds correctly, however once I input a name, nothing happens, and the text file remains empty. Any ideas?

Upvotes: 0

Views: 2666

Answers (1)

languitar
languitar

Reputation: 6784

You request message once and then start a loop looking for a message that is finished. However, if you first entered something different, which will result in message, this condition will never become true.

I suspect you want:

###Adding to an Empty File
filename = 'guest_book.txt'

while True: # checking for value that will end the program
    message = input("Please enter your name for our records: ") # retrieving input
    if message == 'finished':
        break
    with open(filename, 'a') as f:
        f.write(message)

Upvotes: 1

Related Questions