我正在做一些练习,但我无法解决这个问题。
编写一个 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/