Someone Somewhere
Someone Somewhere

Reputation: 37

How do I run while loop that appends a text file?

I'm a beginner trying to do a short learning exercise where I repeatedly prompt users for their name and save those names to guest_book.txt, each name in a new line. So far, while loops are always giving me trouble to get them working properly.

In this case, the program ends when I enter the first name, here's the code:

"""Prompt users for their names & store their responses"""
print("Enter 'q' to quit at any time.")
name = ''
while True:
    if name.lower() != 'q':
        """Get and store name in guestbook text file"""
        name = input("Can you tell me your name?\n")
        with open('guest_book.txt', 'w') as guest:
            guest.write(name.title().strip(), "\n")

        """Print greeting message with user's name"""
        print(f"Well hello there, {name.title()}")
        continue
    else:
        break

It runs perfectly when I omit the with open() block.

Upvotes: 0

Views: 1276

Answers (2)

Andy Pavlov
Andy Pavlov

Reputation: 316

First try to read an error which was shown by Python.

TypeError: write() takes exactly one argument (2 given)

Next you answer a name after if state. I make some changes with your code and move open to begin of code (and thanks to Corralien for review):

print("Enter 'q' to quit at any time.")
with open('guest_book.txt', 'w') as file:
    while True:
        name = input("Can you tell me your name?").title().strip()
        if name.lower() == 'q':
            break
        if name:
            file.write('{}\n'.format(name))
            print('Well hello there, {}'.format(name))

Upvotes: 1

Corralien
Corralien

Reputation: 120419

In a more pythonic way:

with open('guest_book.txt', 'w') as guest:
    while True:
        # Prompt users for their names & store their responses
        name = input("Can you tell me your name?\n")
        if name.lower() == 'q':
            break

        # Get and store name in guestbook text file
        guest.write(f"{name.title().strip()}\n")
        # Print greeting message with user's name
        print(f"Well hello there, {name.title()}")
Can you tell me your name?
Louis
Well hello there, Louis
Can you tell me your name?
Paul
Well hello there, Paul
Can you tell me your name?
Alex
Well hello there, Alex
Can you tell me your name?
q
>>> %cat guest_book.txt
Louis
Paul
Alex

Upvotes: 1

Related Questions