【发布时间】:2020-10-25 15:24:03
【问题描述】:
我正在做一些练习,但我无法弄清楚这一点。
编写一个提示用户输入姓名的 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)
【问题讨论】: