python - 使用 while 循环将用户输出保存到文件

标签 python loops file

我正在做一些练习,但我无法解决这个问题。

编写一个 while 循环,提示用户输入他们的名字。当他们输入自己的名字时,在屏幕上打印一条问候语并在名为 guest_book.txt 的文件中添加一行记录他们的访问。确保每个条目出现在文件中的新行上。

老实说,我在这上面花了很多时间,但我似乎不理解处理文件的逻辑。我认为 f.write 应该直接在 with open 下,以便将用户 input 保存在文件中,但这与我知道。你能帮帮我吗?

我的尝试:

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

我对第二个抱有更多的希望,但仍然行不通。

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)

最佳答案

稍微调整一下即可使您编写的代码正常工作。主要问题是您不能使用 f.write() 的输出作为消息的值,因为它不包含消息,它包含写入文件的字符数,所以它永远不会包含 quit。此外,您希望在检查完 quit 之后执行 write,否则您将向文件写入 quit

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)

注意:我已将 break 更改为 active = False,因为您将其编写为 while active:,但您本来可以只需 while True:break

就可以了

关于python - 使用 while 循环将用户输出保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62740203/

相关文章:

php - "Unfolding"一个字符串

java - 如何读取数字并将数字放入对象数组中

python文件读取 "int too large to convert to c long"

python - 比较 Pandas 系列中的前一个值和下一个值

javascript - 将图像像素数据转换为坐标数组

c++ - 如何在C++中从文本文件中删除相似的值并将其分组?

python - 在Python中读取文件并将列放入数组中

python - Cython 并行性和模板

python - Pygame 知道何时按下 shift+other 键

JavaScript Loop 卡住初学者