如何 运行 while 循环追加文本文件?

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

我是初学者,尝试做一个简短的学习练习,我反复提示用户输入他们的名字并将这些名字保存到 guest_book.txt,每个名字在一个新行中。到目前为止,while 循环总是让我无法正常工作。

在这种情况下,当我输入名字时程序结束,代码如下:

"""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

当我省略 with open() 块时它运行完美。

以更 pythonic 的方式:

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

首先尝试读取 Python 显示的错误。

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

接下来你在if状态后回答一个名字。我对您的代码进行了一些更改并移至代码开头(感谢 Corralien 的审阅):

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))